大家好,我有以下数组
const arr = [
{
ImageFileSet: [{ id: 1 }],
LineItemFile: "new name",
LineItemRef: "PDF",
id: 44
},
{
ImageFileSet: [{ id: 7 }, { id: 8 }, { id: 9 }],
LineItemFile: null,
LineItemRef: "Image"
id: 124
},
];
我正在尝试使用以下代码对新数组中的对象数组进行分组
const allFiles = arr .flatMap(({ ImageFileSet }) => [ImageFileSet]);
输出是
[ { id: 1 }, { id: 7 }, { id: 8 }, { id: 9 } ]
现在我怎样才能为每个对象添加 LineItemFile
?
我想要类似的最终结果
[ { id: 1, LineItemFile: "new name", }, { id: 7,LineItemFile: null, }, { id: 8 ,
LineItemFile: null,}, { id: 9 , LineItemFile: null,} ]
请帮我解决这个问题。
我查看了 this文章,但没有帮助。
最佳答案
你可以这样做
const arr = [{
ImageFileSet: [{
id: 1
}],
LineItemFile: "new name",
LineItemRef: "PDF",
id: 44
},
{
ImageFileSet: [{
id: 7
}, {
id: 8
}, {
id: 9
}],
LineItemFile: null,
LineItemRef: "Image",
id: 124
},
];
const result = arr.flatMap(({ImageFileSet,LineItemFile}) =>
ImageFileSet.map(d => ({ ...d, LineItemFile}))
)
console.log(result)
关于javascript - 如何在 javascript 中为每个分组对象添加新键值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72879398/