[removed] merge objects by key

后端 未结 1 2012
挽巷
挽巷 2021-01-24 05:59

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         


        
相关标签:
1条回答
  • 2021-01-24 06:16

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

    0 讨论(0)
提交回复
热议问题