[英]Concatenate and aggregate json object data with node.js
I generate the following json in my Node application: 我在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'
}
]
I'd now like to concatenate users so that they appear as a single object with the sport
listed in an array and the medal_count
aggegrated for the user. 现在,我想连接用户,以便他们作为单个对象出现,并在数组中列出
sport
,并且为用户medal_count
badge_count。 The above json would look like this: 上面的json看起来像这样:
[ { id: 1,
name: 'user1',
sport: [
'athletics',
'tennis'
],
medal_count: '3'
},
{ id: 2,
name: 'user2',
sport: 'football',
medal_count: '2'
}
]
How is this done? 怎么做? Am I correct in thinking this should be done with a map reduce function?
我认为应该使用map reduce函数来完成此操作是否正确?
Edited 编辑
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);
Yes, you are right: 是的,你是对的:
'use strict'; const data = [{ 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', }]; const out = data.reduce((accumulator, item) => { if (accumulator[item.id]) { const group = accumulator[item.id]; if (Array.isArray(group.sport)) { group.sport.push(item.sport); } else { group.sport = [group.sport, item.sport]; } group.medal_count = `${(+group.medal_count) + (+item.medal_count)}`; } else { accumulator[item.id] = item; } return accumulator; }, {}); console.log(JSON.stringify(out, null, 2));
Note that you are using numbers as strings for medal_count
请注意,您使用数字作为
medal_count
字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.