Merge objects in array based on property

前端 未结 3 1805
悲哀的现实
悲哀的现实 2020-12-21 08:03

I have an array like so which i am trying to merge so any object that has the name property the same will after the merge contain a list of merged objects

va         


        
3条回答
  •  春和景丽
    2020-12-21 08:41

    Firstly you could remove the duplicate entries and organize the objects inside the myList array. Then, return an array of objects with specified keys, based on the ordered object from the first step.

    var array = [{name:"One",myList:['Object1','Object2']},{name:"Two",myList:['Object3','Object4']},{name:"One",myList:['Object5','Object6']}], obj = {};
    
    array.forEach(function(v) {
      obj[v.name] = (obj[v.name] || []).concat(v.myList)
    });
    
    var arr = Object.keys(obj).reduce(function(s,a) {
      s.push({name: a, myList: obj[a]});
      return s;
    }, []);
    
    console.log(arr);

提交回复
热议问题