TrtG TrtG - 2 months ago 7
Javascript Question

Angularjs merge two objects

For instance, from these two objects :

var object1 = {
"color": "yellow",
"size" : null,
"age" : 7,
"weight" : null
}

var object2 = {
"color": "blue",
"size" : 51,
"age" : null
}


I want this (object 2 overrides object 1 except for null properties or properties he doesn't have) :

{
"color": "blue",
"size" : 51,
"age" : 7,
"weight" : null
}

Answer

For Angular 1.x

var mergedObject = angular.extend(object1, object2);

Source:

https://docs.angularjs.org/api/ng/function/angular.extend

If you want to not overwrite with null, you can use this.

==========================================================================

For Angular 2 (ECMAScript 6):

you can use Object.assign():

let movie2 = Object.assign({}, movie1, { episode: 8 });
Comments