合并对象:在javascript中比较和合并两个对象的问题

时间:2019-10-29 01:50:14

标签: javascript arrays object

晚安。一些慈善的灵魂可以帮助我解决有关javascript对象的问题。非常感谢谁能...

...

1 个答案:

答案 0 :(得分:2)

这将起作用,它还会累加匹配language的计数

var arrA = [
    {language:'php', count:5},
    {language:'c', count:7}
];

var arrB = [
    {language:'php', count:0},
    {language:'c', count:0},
    {language:'python', count:0},
    {language:'ace', count:0},
    {language:'electron', count:0},
];

let result = [...arrA, ...arrB].reduce((acc, item) => {
  let found = acc.find(x => x.language=== item.language);
  if (found) {
    found.count += item.count;
  } else {
    acc.push(Object.assign({},item));
  }
  return acc;
}, [])
console.log(result);