How to add properties from one object into another without overwriting in JavaScript?


Let’s say the following are our objects −

var first = {key1: 100, key2: 40, key3: 70}
var second = {key2: 80, key3: 70, key4: 1000}

You can use the concept of hasOwnProperty() to add properties from one object to another. Following is the code −

Example

var first = {key1: 100, key2: 40, key3: 70}
var second = {key2: 80, key3: 70, key4: 1000}
function addPropertiesWithoutOverwritting(first, second) {
   for (var key2 in second) {
      if (second.hasOwnProperty(key2) && !first.hasOwnProperty(key2)) {
         first[key2] = second[key2];
      }
   }
   return first;
}
console.log(addPropertiesWithoutOverwritting(first, second))

To run the above program, you need to use the following command −

node fileName.js.

Output

Here, my file name is demo99.js. This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo99.js
{ key1: 100, key2: 40, key3: 70, key4: 1000 }

Updated on: 07-Sep-2020

527 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements