我有一个数据数组:
const data = [
{
groupName: 'groupName1',
types: [
{
name: 'name1',
displayName: 'displayName1'
},
{
name: 'name2',
displayName: 'displayName2'
},
]
},
{
groupName: 'groupName2',
types: [
{
name: 'name3',
displayName: 'displayName3'
},
{
name: 'name4',
displayName: 'displayName4'
},
]
},
]
我需要转换这个数组,以便向每个对象添加一个额外的groupName字段。输出应该是一个包含对象的数组,如下所示:
const resultData = [
{
groupName: 'groupName1',
name: 'name1',
displayName: 'displayName1'
},
{
groupName: 'groupName1',
name: 'name2',
displayName: 'displayName2'
},
{
groupName: 'groupName2',
name: 'name3',
displayName: 'displayName3'
},
{
groupName: 'groupName2',
name: 'name4',
displayName: 'displayName4'
},
]
我尝试通过map数组方法
const data = [{"groupName":"groupName1","types":[{"name":"name1","displayName":"displayName1"},{"name":"name2","displayName":"displayName2"}]},{"groupName":"groupName2","types":[{"name":"name3","displayName":"displayName3"},{"name":"name4","displayName":"displayName4"}]}]
const resultData = data.map((item) => {
item.types.map((item1) => {
return {
...item1,
groupName: item.groupName
}
})
return item
})
console.log(resultData)
但是这并没有返回我需要的数组。请告诉我如何转换这个数组,使每个对象都有正确的结构?提前感谢!
将外部的Array.map()
调用替换为Array.flatMap()
以创建一个平面数组,并返回内部map调用的结果,而不是原始项。
const data = [{"groupName":"groupName1","types":[{"name":"name1","displayName":"displayName1"},{"name":"name2","displayName":"displayName2"}]},{"groupName":"groupName2","types":[{"name":"name3","displayName":"displayName3"},{"name":"name4","displayName":"displayName4"}]}]
const resultData = data.flatMap(({ types, groupName }) =>
types.map(item => ({
...item,
groupName
}))
)
console.log(resultData)
我会用reduce
。
data.reduce((carry, {types, groupName}) => carry.concat(types.map(d => ({...d, groupName}))), []);