[英]How to add / replace values in a nested object (without losing original references) in Javascript?
I have to update a nested object with the new data without losing references in the original object. 我必须使用新数据更新嵌套对象,而不会丢失原始对象中的引用。 I think my problem is best explained with an example:
我认为我的问题最好用一个例子来解释:
Original Object: 原始对象:
{
"one": 1,
"two": {
"three": 3,
"four": {
"five": 5
}
}
}
Update object: 更新对象:
{
"two": {
"three": 5,
"four": {
"five": 7,
"new": 8
}
}
}
Final object: (while retaining references in original object) 最终对象:(同时保留原始对象中的引用)
{
"two": {
"three": 5,
"four": {
"five": 7,
"new": 8
}
}
}
So while it may look like the Update object and Final object are exactly the same, the thing to note is that I have to keep the references from the original object (ie I don't replace the "two" object or the "four" object inside the "two" object, only update their values). 因此虽然它可能看起来像Update对象和Final对象完全相同,但要注意的是我必须保留原始对象的引用(即我不替换 “两个”对象或“四个”对象里面的“两个”对象,只更新它们的值)。
The reason for preserving references is that because I'm using the data structure to create various bindings in AngularJS. 保留引用的原因是因为我正在使用数据结构在AngularJS中创建各种绑定。 I've tried using
angular.copy
but it does not give me the desired effect. 我尝试过使用
angular.copy
但它并没有给我带来理想的效果。 Also if there is a pure JS implementation for this, I'd love to see it so that I can learn from the code. 此外,如果有一个纯粹的JS实现,我很乐意看到它,以便我可以从代码中学习。
What is the most efficient way to accomplish this? 实现这一目标的最有效方法是什么?
Maybe this works for you. 也许这适合你。 First the unwanted keys are deleted and then the values updated.
首先删除不需要的密钥,然后更新值。
function deep(o, u) { var keysO = Object.keys(o), keysU = Object.keys(u); keysO.forEach(function (k) { if (-1 === keysU.indexOf(k)) { delete o[k]; } }); keysU.forEach(function (k) { if (u[k] !== null && typeof u[k] === 'object') { if (o[k] === null || typeof o[k] !== 'object') { o[k] = {}; } deep(o[k], u[k]); return; } o[k] = u[k]; }); } var original = { one: 1, two: { three: 3, four: { five: 5 } } }, update = { two: { three: 5, four: { five: 7, "new": 8 } } }; deep(original, update); console.log(original);
Clone the object and then update the properties what you need. 克隆对象,然后更新所需的属性。
Objects are passed by reference and hence it should be cloned. 对象通过引用传递,因此应该克隆它。
To clone: 要克隆:
Object.assign(target, sources...);
var originalObj = {a: 1, b: 2, c: 3};
var updatedObj = {};
Object.assign(updatedObj, originalObj);
now you can update the updatedObj and the originalObj will be preserved. 现在您可以更新updatedObj并保留originalObj。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.