javascript - Merging JS array of objects -
ok have 2 objects want merge wondering best way is...
obj1 = [ { id: 123, list: [ {id:1}, {id:2}, {id: 3} ] }, { id: 456 list: [ {id:99}, {id:98}, {id: 97} ] } ] obj1 = [ { id: 123, list: [ {id:1}, {id:4}, {id: 5} ] }, { id: 456 list: [ {id:99}, {id:100}, {id: 101} ] } ]
i able call merge(obj1, obj2)
, result like:
resultobj = [ { id: 123, list: [ {id:1}, {id:2}, {id:3}, {id:4}, {id: 5} ] }, { id: 456 list: [ {id:99}, {id:98}, {id:97}, {id:100}, {id: 101} ] } ]
you can use foreach()
group elements id on first level , 1 more foreach()
, find()
check objects in list , push array or assign existing object same id.
var obj1 = [{"id":123,"list":[{"id":1},{"id":2},{"id":3}]},{"id":456,"list":[{"id":99},{"id":98},{"id":97}]}] var obj2 = [{"id":123,"list":[{"id":1},{"id":4},{"id":5}]},{"id":456,"list":[{"id":99},{"id":100},{"id":101}]}] var result = [] var arr = [].concat(obj1, obj2) arr.foreach(function(e) { if(!this[e.id]) result.push(this[e.id] = e) else { var = this; e.list.foreach(function(a) { var o = that[e.id].list.find(c => a.id == c.id); o ? object.assign(o, a) : that[e.id].list.push(a) }) } }, {}) console.log(result)
Comments
Post a Comment