合并两个单独的 JavaScript 对象的属性的最佳方法是什么?
我有一个 javascript 对象,我想用另一个对象的数据更新它。我想从新对象添加新内容,使用新对象更新旧内容,并保留旧对象中不存在于新对象中的任何内容。 (底部的示例)
我尝试了各种方法,但它们要么完全覆盖对象,要么在不手动为对象中的对象中的对象写出循环的情况下不级联,等等。
我还考虑过一个递归函数,该函数将迭代属性,检查它内部是否有另一个对象,以及它是否在更新对象时调用自身。 (还没有写,希望更清晰)
var obj1 = {id:1, name:"asdf", info:{first:3, secondary:{deeper:3} } };
var obj2 = {id:1, info:{first: 3, secondary:{deeper:5, new_deeper:6},third:7}, new_info:7};
我想做所以 obj1 相当于:
{id:1, name:"asdf", info:{first:3, secondary:{deeper:5, new_deeper:6},third:7}, new_info:7};< /code>
预先感谢您!
I have a javascript object that I would like to update with data from another object. I want to add new things from the new object, update old things using the new object and leave alone anything in the old object that is not in the new object. (Example at the bottom)
I have tried various ways but they either overwrite the object completely or they do not cascade without manually writing out loops for objects in objects in objects, etc.
I have also thought about a recursive function that will iterate over the properties, check if it has another object inside itself and if it does call itself all while updating the object. (have not written it, in hopes of something cleaner)
var obj1 = {id:1, name:"asdf", info:{first:3, second:{deeper:3} } };
var obj2 = {id:1, info:{first: 3, second:{deeper:5, new_deeper:6}, third:7}, new_info:7};
I would like to make it so obj1 be equivalent to:
{id:1, name:"asdf", info:{first:3, second:{deeper:5, new_deeper:6}, third:7}, new_info:7};
Thank you in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我知道建议使用库并不总是一个好的答案,但是 jQuery 有一个
$.extend
方法,它是执行此操作的杀手锏。如果您检查该库,您可以获取该功能并将其用于您自己的东西。
http://code.jquery.com/jquery-1.7.1.js
I know suggesting a library isn't always a great answer, but jQuery has an
$.extend
method that is killer for doing this.If you check the library you could grab just that functionality and use it for your own stuff.
http://code.jquery.com/jquery-1.7.1.js