Milos
Milos

Reputation: 1263

How to add a property from another object if it doesn't exist in the first object in JavaScript

I have two objects, obj1 and obj2. If obj2 has a key that obj1 doesn't have, that obj2 key/value pair gets added to obj1.

for example:

obj1 = {
a:1,
b:2
}
obj2 = {
b:4,
c:3
}

c:3 would be put into obj1.

Here's what I have as an attempt, but my brain is being run in circles by this. I can't modify the 2nd object at all (don't need to), and i have to keep the value in obj1 if it also exists in obj2.

function extend(obj1, obj2) {
  
  function comparison(obj1,obj2){
      var object1keys = Object.keys(obj1)
      var object2keys = Object.keys(obj2)
      var flag = 0
      for(var i = 0; i<object2keys.length;i++){
          flag = 0
          for(var j = 0; j<object1keys.length;j++){
              if(object2keys[i] === object1keys[j]){
                  flag = 1
                  console.log(i,j)
                  break
              }
              if(flag = 0 && j == object1keys.length - 1){
                  obj1[i] = obj2[j]
              }
          }
      }
      return obj1
  }
 return obj1
}
Edit:This is a unique question because it looked like the other question didn't involve adding a specific key:value pair that didn't exist.

Upvotes: 1

Views: 1181

Answers (2)

Piyush
Piyush

Reputation: 1162

This should work.

function extend(obj1, obj2) {
  Object.keys(obj2).forEach(function(key) {
    obj1[key] = obj2[key];
  })
  return obj1;
}

console.log(extend({
  a: 1,
  b: 2
}, {
  b: 3,
  c: 4
}))

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Simple solution using Object.keys() and Object.hasOwnProperty() functions:

var obj1 = {a:1,b:2}, obj2 = {b:4,c:3};

Object.keys(obj2).forEach(function(k) {
  if (!obj1.hasOwnProperty(k)) obj1[k] = obj2[k];
});

console.log(obj1);

Upvotes: 4

Related Questions