Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge 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 (object2 overrides object1 except for null properties or properties he doesn't have):

{
  "color": "blue",
  "size": 51,
  "age": 7,
  "weight": null
}
like image 616
TrtG Avatar asked Feb 12 '15 09:02

TrtG


People also ask

How do I combine multiple objects into one?

To merge objects into a new one that has all properties of the merged objects, you have two options: Use a spread operator ( ... ) Use the Object. assign() method.

How do you combine objects in JavaScript?

The easiest way to merge two objects in JavaScript is with the ES6 spread syntax / operator ( ... ). All you have to do is insert one object into another object along with the spread syntax and any object you use the spread syntax on will be merged into the parent object.

How do you merge objects in TypeScript?

Use the spread syntax (...) to merge objects in TypeScript, e.g. const obj3 = { ... obj1, ... obj2 } . The type of the final object will successfully be inferred, so trying to add or remove properties from it will cause the type checker to show an error.


3 Answers

Copy

var src = { name: 'Apple', price: 5}; var dst= angular.copy(src); 
  • deep copy

Extend:

var mergedObject = angular.extend(dst, src1, src2, ...)  
  • shallow copy

Merge:

var mergedObject = angular.merge(dst, src); 
  • since angular 1.4+
  • deep (recursively) copy

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


Object.assign():

let movie2 = Object.assign({}, movie1, { episode: 8 }); 
  • fot Angular 2+ (ECMAScript 6)

Sources:

  • https://docs.angularjs.org/api/ng/function

  • http://davidcai.github.io/blog/posts/copy-vs-extend-vs-merge/

like image 101
Beri Avatar answered Oct 06 '22 08:10

Beri


For newer versions (at least 1.4.0) of angular you can use angular.merge

Unlike extend(), merge() recursively descends into object properties of source objects, performing a deep copy.

like image 44
Rafael P. Miranda Avatar answered Oct 06 '22 07:10

Rafael P. Miranda


Using angualr.extend will not produce the result requested. The object2.age null value will override object1.age value.

angular.extend(object1, object2) will produce the following result:

{
    "color" : "blue", 
    "size" : 51, 
    "age" : null,   <=== undesirable result
    "weight" : null
}

Use the following code to skip over null properties

for (var prop in object1) {
    if(object1.hasOwnProperty(prop) && object2.hasOwnProperty(prop) && object2[prop]!=null) {
        object1[prop] = object2[prop];
    }
}

This will produce the following requested result

{
    "color" : "blue", 
    "size" : 51, 
    "age" : 7, 
    "weight" : null
}
like image 21
Saeed D. Avatar answered Oct 06 '22 08:10

Saeed D.