javascript - Merge objects in array based on property -
i have array trying merge object has name property same after merge contain list of merged objects
var array = [ {name: "one", mylist: [object1, object2] }, {name: "two", mylist: [object3, object4] }, {name: "one", mylist: [object5, object6] } ]
how merge 2 'one' objects
var array = [ {name: "one", mylist: [object1, object2, object5, object6] }, {name: "two", mylist: [object3, object4] } ]
looking in vanilla javascript
firstly remove duplicate entries , organize objects inside mylist
array. then, return array of objects specified keys, based on ordered object 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);
Comments
Post a Comment