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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:41:18  来源:igfitidea点击:

Update values from one object to another in node JS

javascriptnode.jsobjectpropertieskey

提问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 NodeJSto do this, instead of writing our own code.

是否有任何内置函数NodeJS来执行此操作,而不是编写我们自己的代码。

Thanks and Regards,

谢谢并恭祝安康,

Varun

瓦伦

回答by tymeJV

Simple forloop

简单for循环

for (var key in j2) { j1[key] = j2[key]; }

Demo: http://jsfiddle.net/tymeJV/kthVf/

演示:http: //jsfiddle.net/tymeJV/kthVf/

回答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++"}