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"
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…