0

I have two JSON objects as follows.

var j1 = {name: 'Varun', age: 24};
var j2 = {code: 'NodeJS', alter: 'C++'}

I need to update JSON j1 with j2.

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.

Thanks and Regards,

Varun

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
Varun kumar
  • 2,849
  • 3
  • 15
  • 9
  • 1
    [Please use the searchbox](http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically) – user703016 Sep 20 '13 at 14:04

2 Answers2

5

Simple for loop

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

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

tymeJV
  • 103,943
  • 14
  • 161
  • 157
2

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++"}
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
  • 1
    I like your answer because you are using a function. What I don't really like is that you are not checking if the property is really owned by the object ... and you should probably return a new object. – Silviu Burcea Sep 20 '13 at 14:20