我在 Node 应用程序中生成以下 json:
[ { id: 1,
name: 'user1',
sport: 'athletics',
medal_count: '1'
},
{ id: 1,
name: 'user1',
sport: 'tennis',
medal_count: '2'
},
{ id: 2,
name: 'user2',
sport: ['football'],
medal_count: '2'
}
]
我现在想要将用户连接起来,以便它们显示为单个对象,其中包含数组中列出的 sport
以及为用户聚合的 medal_count
。上面的 json 看起来像这样:
[ { id: 1,
name: 'user1',
sport: [
'athletics',
'tennis'
],
medal_count: '3'
},
{ id: 2,
name: 'user2',
sport: 'football',
medal_count: '2'
}
]
这是如何完成的?我认为这应该使用 map 缩减功能来完成是否正确?
最佳答案
已编辑
let input = [{
id: 1,
name: 'user1',
sport: 'athletics',
medal_count: '1'
},
{
id: 1,
name: 'user1',
sport: 'tennis',
medal_count: '2'
},
{
id: 2,
name: 'user2',
sport: 'football',
medal_count: '2'
}
];
let grouped = {};
input.forEach(({id, name, sport, medal_count}) => {
grouped[id] = grouped[id] || {id, name, sport: [], medal_count:0};
if (!grouped[id].sport.includes(sport))
grouped[id].sport.push(sport);
grouped[id].medal_count = `${(+grouped[id].medal_count)+ (+medal_count)}`;
});
grouped = Object.values(grouped);
console.log(grouped);
关于javascript - 使用 Node.js 连接和聚合 json 对象数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56044483/