javascript 在节点 JS 中将值从一个对象更新到另一个对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18918694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Update values from one object to another in node JS
提问by Varun kumar
I have two JSON objects as follows.
我有两个 JSON 对象,如下所示。
var j1 = {name: 'Varun', age: 24};
var j2 = {code: 'NodeJS', alter: 'C++'}
I need to update JSON j1 with j2.
我需要用 j2 更新 JSON j1。
Desired output
期望输出
{name: 'Varun', age: 24, code: 'NodeJS', alter: 'C++'};
Is there any inbuild function in NodeJS
to do this, instead of writing our own code.
是否有任何内置函数NodeJS
来执行此操作,而不是编写我们自己的代码。
Thanks and Regards,
谢谢并恭祝安康,
Varun
瓦伦
回答by tymeJV
Simple for
loop
简单for
循环
for (var key in j2) { j1[key] = j2[key]; }
回答by Abdennour TOUMI
yes, you can implement your own function of inheritance :
是的,您可以实现自己的继承功能:
function inherits(base, extension)
{
for (var property in base)
{
try
{
extension[property] = base[property];
}
catch(warning)
{
}
}
};
then
然后
inherits(j2,j1)
console.log(j1)
// Object {name: "Varun", age: 24, code: "NodeJS", alter: "C++"}