Search code examples
javascriptangularjsmergejavascript-objectsextends

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
}

Solution

  • 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: