用node.js连接和聚合json对象数据

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (127)

我在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为用户进行aggegrated。上面的json看起来像这样:

    [ { id: 1,
        name: 'user1',
        sport: [
          'athletics',
          'tennis'
        ],
        medal_count: '3' 
      },
      { id: 2,
        name: 'user2',
        sport: 'football',
        medal_count: '2' 
      }
    ]

这是怎么做到的?我是否正确认为应该使用map reduce函数?

提问于
用户回答回答于

编辑

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);
用户回答回答于

是的,你是对的:

'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));

请注意,您使用数字作为字符串 medal_count

扫码关注云+社区

领取腾讯云代金券