2 回答

TA貢獻(xiàn)1890條經(jīng)驗(yàn) 獲得超9個(gè)贊
您必須獨(dú)立于循環(huán)管理子級(jí)的索引。那這個(gè)呢?
let i = 0;
return parentArr.map((parent) => {
return {
name: parent.name,
additionalData: parent.childArray.map((child) => ({
name: child.name
index: i++
})),
};
});

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
索引計(jì)數(shù)應(yīng)位于地圖外部,因?yàn)檫@將在每次迭代時(shí)重置它。
您可以將此行為抽象為可重用的方法,如下所示。
const parentArr = [
{
name: 'first parent array',
childArray: [
{
name: '1 / first child'
},
{
name: '1 / second child'
}
]
},
{
name: 'second parent array',
childArray: [
{
name: '2 / first child array'
},
{
name: '2 / second child array'
}
]
}
];
const transformArray = root => {
let i = 0;
return root.map(({ name, childArray }) => ({
name,
additionalData: childArray.map(({ name }) => ({
index: i++,
name
}))
}));
};
console.log(transformArray(parentArr));
添加回答
舉報(bào)