deep merge objects with AngularJS

Angular 1.4 or later

Use angular.merge:

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

angular.merge(object1, object2); // merge object 2 into object 1

Older versions of Angular:

There is no reason a simple recursive algorithm shouldn’t work 🙂

Assuming they’re both the result of JSON.stringify or similar:

function merge(obj1,obj2){ // Our merge function
    var result = {}; // return result
    for(var i in obj1){      // for every property in obj1 
        if((i in obj2) && (typeof obj1[i] === "object") && (i !== null)){
            result[i] = merge(obj1[i],obj2[i]); // if it's an object, merge   
        }else{
           result[i] = obj1[i]; // add it to result
        }
    }
    for(i in obj2){ // add the remaining properties from object 2
        if(i in result){ //conflict
            continue;
        }
        result[i] = obj2[i];
    }
    return result;
}

Here is a working fiddle

(Note, arrays are not handled here)

Leave a Comment

tech