gpt4 book ai didi

javascript - 在对象数组中创建缩减集和嵌套数组

转载 作者:行者123 更新时间:2023-11-30 10:57:38 25 4
gpt4 key购买 nike

我正在努力将“平面”对象数组转换为压缩但嵌套的版本:

const startingArray = [
{ name: 'one', id: 100, thing: 1 },
{ name: 'one', id: 100, thing: 2 },
{ name: 'one', id: 100, thing: 4 },
{ name: 'two', id: 200, thing: 5 }
];

/*
desiredResult = [
{name: 'one', id:100, things: [
{thing: 1}, {thing: 2}, {thing:4}
]},
{name: 'two', id:200, things: [
{thing: 5}
]}
]
*/

// THIS DOES NOT WORK
const result = startingArray.reduce((acc, curr) => {
if (acc.name) {
acc.things.push(curr.thing)
}
return { name: curr.name, id: curr.id, things: [{thing: curr.thing}] };
}, {});

我有什么不明白的?!

最佳答案

在您的 reduce 回调中,acc 不是“数组的每个元素”(curr 是什么)或“结果中的匹配元素”(您有自己确定),它是每次调用函数时转换的累积对象。

也就是说,当你返回{name: curr.name, id: curr.id, things: [{thing: curr.thing}] };时,它设置 acc 到该对象以进行下一次迭代,丢弃之前包含在其中的任何数据 - acc.name 将永远保留迭代的姓氏,结果永远不会累积成任何有意义的东西.

您要做的是将结果累积到一个数组中(因为这是您想要的输出),确保每次迭代都返回该数组:

const startingArray = [
{ name: 'one', id: 100, thing: 1 },
{ name: 'one', id: 100, thing: 2 },
{ name: 'one', id: 100, thing: 4 },
{ name: 'two', id: 200, thing: 5 }
];

const result = startingArray.reduce((acc, curr) => {
let existing = acc.find(o => o.id == curr.id);
if(!existing) acc.push(existing = { name: curr.name, id: curr.id, things: [] });
existing.things.push({thing: curr.thing});
return acc;
}, []);

console.log(result);

由于您想要的结果格式,这涉及相当多的 acc.find() 调用,这是昂贵的 - 您可以使用这个技巧以简洁的方式解决这个问题,使用第一个元素累加器数组作为 id 到引用的映射(也具有 ES6 解构):

const startingArray = [
{ name: 'one', id: 100, thing: 1 },
{ name: 'one', id: 100, thing: 2 },
{ name: 'one', id: 100, thing: 4 },
{ name: 'two', id: 200, thing: 5 }
];

const result = startingArray.reduce((acc, {name, id, thing}) => {
if(!acc[0][id])
acc.push(acc[0][id] = { name, id, things: [] });
acc[0][id].things.push({thing});
return acc;
}, [{}]).slice(1); //slice off the mapping as it's no longer needed

console.log(result);

关于javascript - 在对象数组中创建缩减集和嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59364163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com