ralftar
ralftar

Reputation: 135

Update a JSON formatted JavaScript object based on another

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.

Upvotes: 0

Views: 69

Answers (3)

Murthy
Murthy

Reputation: 387

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]

Upvotes: 0

Cyril Cherian
Cyril Cherian

Reputation: 32327

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;
}

Upvotes: 1

kTT
kTT

Reputation: 1350

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

Upvotes: 1

Related Questions