0

I want to merge object1 and object2 into object3. The values corresponding to the keys matching should be updated and the unmatching keys should be ignored. How to do it?

var object1 = {
  "pii" : "val1",
  "loc" : "val2"
}

var object2 = {
  "rrb" : "val3",
  "voc" : "val4"
}

var object3{
 "pii": "",
      "loc" : "",
     "rrb" : "",
      "voc" : "",
      "obj3item" : "",
      "obj3val" : ""
}

Result object

var object3 ={
  "pii": "val1",
  "loc" : "val2",
 "rrb" : "val3",
  "voc" : "val4",
  "obj3item" : "val5",
  "obj3val" : "item4"

}
neelmeg
  • 2,459
  • 6
  • 34
  • 46
  • See http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically – Matthias Mar 08 '16 at 19:29

1 Answers1

1

You are basically extending an object.

This code will do your job:

function merge_options(obj1,obj2){
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
}
angussidney
  • 686
  • 2
  • 13
  • 24
Rahul Gaba
  • 460
  • 4
  • 6