How to merge objects?
Asked Answered
J

3

40

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
}
Juridical answered 12/2, 2015 at 9:18 Comment(0)
S
65

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:

Soph answered 12/2, 2015 at 9:21 Comment(3)
Using angualr.extend will not produce the result requested. The object2.age null value will override object1.age value.Investigator
@SaeedD.true, but there is already a way to fix this. Check my link in update section.Soph
Worth noting: angular extend and merge are way different. One is shallow other is deep.Theca
T
18

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.

Thessa answered 2/6, 2015 at 16:40 Comment(0)
I
4

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
}
Investigator answered 27/3, 2015 at 2:49 Comment(1)
I found the discussion while googling the difference of extend and merge. In the case, we can use your code or call angular.merge if we have angular 1.4.x.Cuneal

© 2022 - 2024 — McMap. All rights reserved.