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"

}
1

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.