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

时间:2019-05-08 15:45:55

标签: javascript arrays node.js json

我在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 reduce函数来完成此操作吗?

2 个答案:

答案 0 :(得分:2)

已编辑

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

答案 1 :(得分:1)

是的,您是对的:

'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

的字符串