简体   繁体   English

Javascript:按键合并对象

[英]Javascript: merge objects by key

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}
]

I want to merge array elements by id.我想通过 id 合并数组元素。 The result should look like this:结果应如下所示:

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

Right now, I'm doing this with a for loop and a lot of if and else .现在,我正在用一个for 循环和很多 if 和 else来做这件事。

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).我试过用谷歌搜索这个,问题是我不确定谷歌是什么(我是一个javascript新手)。 Any help is appreciated.任何帮助表示赞赏。

try this:尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM