合并JavaScript对象重复项

时间:2019-11-29 06:31:01

标签: javascript object

我想将其余的值与Javascript对象中的相同键连接在一起。 想使用香草脚本或lodash解决它。.

示例:

obj = [
  { M: 'M1', F: '123-test-123', CODE: 'A' },
  { M: 'M1', F: '123-test-123', CODE: 'B' },
  { M: 'M1', F: '123-test-123', CODE: 'C' },
  { M: 'M2', F: '123-test-456', CODE: 'A' },
  { M: 'M2', F: '123-test-456', CODE: 'A' }
  ...
]

所需结果:

obj = [
  { M: 'M1', F: '123-test-123', CODE: 'A,B,C' },
  { M: 'M2', F: '123-test-456', CODE: 'A,B' },
  ...
]

谢谢!

1 个答案:

答案 0 :(得分:5)

您可以使用Array.reduce()获得所需的输出:

var obj = [
  { M: 'M1', F: '123-test-123', CODE: 'A' },
  { M: 'M1', F: '123-test-123', CODE: 'B' },
  { M: 'M1', F: '123-test-123', CODE: 'C' },
  { M: 'M2', F: '123-test-456', CODE: 'A' },
  { M: 'M2', F: '123-test-456', CODE: 'A' }
];

var res = obj.reduce((acc, item) => {
  let existItem = acc.find(({M, F}) => M === item.M && F === item.F);
  if(existItem) {
    existItem.CODE += ',' + item.CODE;
  } else {
    acc.push(item);
  }
  return acc;
}, []);

console.log(res);

使用Array.reduce()之外的另一种方法:

var obj = [
  { M: 'M1', F: '123-test-123', CODE: 'A' },
  { M: 'M1', F: '123-test-123', CODE: 'B' },
  { M: 'M1', F: '123-test-123', CODE: 'C' },
  { M: 'M2', F: '123-test-456', CODE: 'A' },
  { M: 'M2', F: '123-test-456', CODE: 'A' }
];

var resObj = {};

obj.forEach((item) => {
  let settingValues = resObj[item.M] ? 
    resObj[item.M].CODE += ',' + item.CODE :
    resObj[item.M] = item;
});

console.log(Object.values(resObj));