Normally to shallow copy objects I would use angular.extend()
Here's an example of that:
var object1 = {
"key": "abc123def456",
"message": {
"subject": "Has a Question",
"from": "[email protected]",
"to": "[email protected]"
}
};
var object2 = {
"key": "00700916391"
};
console.log(angular.extend({}, object1, object2));
Would give us:
{
"key": "00700916391",
"message": {
"subject": "Has a Question",
"from": "[email protected]",
"to": "[email protected]"
}
}
But what if I wanted to merge objects so that parent keys are not over written by child objects:
var object1 = {
"key": "abc123def456",
"message": {
"subject": "Has a Question",
"from": "[email protected]",
"to": "[email protected]"
}
};
var object2 = {
"key": "00700916391", //Overwrite me
"message": { //Dont overwrite me!
"subject": "Hey what's up?", //Overwrite me
"something": "something new" //Add me
}
};
console.log(merge(object1, object2));
Would give us:
{
"key": "00700916391",
"message": {
"subject": "Hey what's up?",
"from": "[email protected]",
"to": "[email protected]",
"something": "something new"
}
}
Is there an Angular function that already does a deep merge that I am not aware of?
If not is there a native way to do this in javascript recursively for n levels deep?
n
objects as paramters. Similarly to howangular.extend()
works... Up to the challenge ? :) – Prairial