Javascript:按键合并对象 [英] Javascript: merge objects by key

查看:53
本文介绍了Javascript:按键合并对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的对象数组:

I have an array of objects that looks like this:

var countries = [
    {id: SWE, value: 5},
    {id: DE, value:10},
    {id: SWE, anotherValue: 11},
    {id: DE, anotherValue: 15}
]

我想通过 id 合并数组元素.结果应该是这样的:

I want to merge array elements by id. The result should look like this:

countries = [
    {id: SWE, value: 5, anotherValue: 11},
    {id: DE, value:10, anotherValue:15}
]

现在,我正在使用 for 循环和大量 if 和 else 来执行此操作.

Right now, I'm doing this with a for loop and a lot of if and else.

问题:是否有任何(更优雅的)javascript 内置功能来实现这一点?

Question: is there any (more elegant) javascript inbuilt functionality to achieve this?

我试过用谷歌搜索这个,问题是我不知道谷歌是什么(我是一个javascript新手).任何帮助表示赞赏.

I've tried googling this, the problem is that I'm not sure what to Google for (I'm a javascript newby). Any help is appreciated.

推荐答案

试试这个:

function mergeById(a){
  var obj={};
  
  a.forEach(function(e){
    if(e && e.id){
      obj[e.id] = obj[e.id] || {};    
      for(var _k in e) obj[e.id][_k] = e[_k]
    }
  });       
  
  return Object.keys(obj).map(function (key) {return obj[key]});
}

var countries = [
    {id: 'SWE', value: 5},
    {id: 'DE', value:10},
    {id: 'SWE', anotherValue: 11},
    {id: 'DE', anotherValue: 15}
]
document.write(JSON.stringify(mergeById(countries)))

这篇关于Javascript:按键合并对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆