组合数组,但如果找到“名称”组合/添加数据

时间:2018-06-17 10:25:07

标签: javascript arrays

我试图在javascript中添加数据时组合2个数组(如果存在的话)。我无法让它发挥作用。我想要做的是添加这个数组:

[  
   {  
  "name":"name1",
  "points":{  
     "intern":57,
     "extern":0,
     "total":57
  }
   },
   {  
  "name":"name2",
  "points":{  
     "intern":26,
     "extern":0,
     "total":26
  }
 }
]

有了这个:

[  
   {  
      "name":"name1",
      "points":{  
         "intern":31,
         "extern":0,
         "total":31
      }
   }
]

但如果“name1”已经在第一个数组中,我想添加实习点和外部点,所以它看起来像这样:

[  
   {  
  "name":"name1",
  "points":{  
     "intern":88,
     "extern":0,
     "total":88
  }
   },
   {  
  "name":"name2",
  "points":{  
     "intern":26,
     "extern":0,
     "total":26
  }
 }
]

我怎样才能在javascript中执行此操作? 谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

使用名称哈希表来查找欺骗:

 const hash = {}, result = [];

 for(const { name, points: {intern, extern, total}} of array1.concat(array2)) {
   if(hash[name]) {
     hash[name].intern += intern;
     hash[name].extern += extern;
     hash[name].total += total;
  } else {
     result.push(hash[name] = {name, intern, extern, total});
  }
}