0

I have seen _.zip which merges two lists based on index but instead I would like merge by key. The two lists are not necessarily sorted/indexed but will have same number of objects

for example

list1 = [{id:"1", field1:"field1val"},...]
list2 = [{id:"1", field2:"field2val"},...]

merge would look like:

 mergeOfList1List2 = [{id:"1", field1:"field1val", field2:"field2val"},...]
Fazeel
  • 26
  • 6
  • Once I have pair of object then i would look at something like _.extend(pair[1].toJSON(), pair[0]) – Fazeel Jun 08 '17 at 16:47
  • Possible duplicate of [How to merge two object values by keys](https://stackoverflow.com/questions/18498801/how-to-merge-two-object-values-by-keys) – Heretic Monkey Jun 08 '17 at 16:54

1 Answers1

0

You can compare and merge like this. Though it is not generic, it would work in your case

list1 = [{id:"1", field1:"field1val"},{id:"2", field1:"abc"}]
list2 = [{id:"1", field2:"field2val"}]

for(var i=0; i<list2.length; i++){
  for(var j=0; j<list1.length; j++){
    if(list1[j].id === list2[i].id){
      list1[j].field2 = list2[i].field2
    }
  }
}

console.log(list1)

A better solution is this as it would combine objects completely(Union) even if there are more properties

list1 = [{id:"1", field1:"field1val"},{id:"2", field1:"abc"}]
list2 = [{id:"1", field2:"field2val"}]

for(var i=0; i<list2.length; i++){
  for(var j=0; j<list1.length; j++){
    if(list1[j].id === list2[i].id){
      Object.assign(list1[j],list2[i])    // to union two objects
    }
  }
}

console.log(list1)
Gaurav Chaudhary
  • 1,491
  • 13
  • 28