0

Having two JSON formatted js-objects:

obj1 = { prop1: 1,
         prop2: 2,
         prop3: 3 }

obj2 = { prop1: 1,
         prop2: 3 }

What is the best js-practise to update obj2 into obj1, that also removes properties? Typically in a jQuery/angular context. Resulting in:

obj1 = { prop1: 1,   // not updated, nor overwritten
         prop2: 3    // updated
       }             // prop3 removed

Must also deal with nested objects and arrays.

5
  • If you are deleting the properties not present in obj2 from obj1. Then you always ending up with obj2. What i mean is that resulting json will always be obj2 irrespective of what obj1 has. Could you please provide a better example. Commented Jun 5, 2015 at 10:22
  • I have been looking into both jquery's and angular's extend functions, but these does not delete removed properties. Commented Jun 5, 2015 at 10:22
  • What @CyrilCherian is trying to say is that it sounds illogical what you're trying to do, because you can actually just type: obj1 = obj2; and will do what you asked. Commented Jun 5, 2015 at 10:25
  • That is correct, Cyril Cheria. But then obj1 is changed to obj2. I need to keep obj1 since it has attached listeners. Commented Jun 5, 2015 at 10:26
  • 1
    Can't you just reattach the listeners? Can you update your question with another example or deeper explanation about what you're trying to do? Commented Jun 5, 2015 at 10:30

3 Answers 3

1

Try this:

function merge_objects(obj1,obj2){
    for (var attr in obj2) { obj1[attr] = obj2[attr]; }
    for (var attr in obj1) { if(!obj2[attr]){ delete obj1[attr]} }
    return obj1;
}
Sign up to request clarification or add additional context in comments.

2 Comments

This should work, with two comments: don't forget to check for hasOwnProperty and watch out for the case obj2 has the property "attr" but it is "false" or "undefined" or 0: your condition will evaluate to "true" and the property will be deleted from obj1... try something like if (!(obj2.hasOwnProperty(attr))) { delete obj1[attr] } instead :)
Thanks Cyril and Octav. I'll go with a recursive version of this.
1

To compare objects you can use angular.equals(obj1, obj2). For merging you can check angular.extend but it won't delete missing elements.

Comments

0

If you want to copy(or clone including arrays/child objects) contents of object2 into object1, try using jquery extend()

Please find jsfiddle [here][2]

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.