Add property to the object from the another object

Add property to the object from the another object
0

#1

hello,
the second day I’m struggling with one task.
the condition of task. is

Write a function called “extend”.
Given two objects, “extend” adds properties from the 2nd object to the 1st object.
Notes:
* Add any keys that are not in the 1st object.
* If the 1st object already has a given key, ignore it (do not overwrite the property value).
* Do not modify the 2nd object at all.

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

extend(obj1, obj2);

console.log(obj1); // --> {a: 1, b: 2, c: 3}
console.log(obj2); // --> {b: 4, c: 3}

At first I’m trying to compare obj1 and obj2 keys
I tryide to compare it with for( ){for(){ }} loops but it

var aProps = Object.keys(obj1);
  var bProps = Object.keys(obj2);
for(var i = 0; i < aProps.length; i++){
  for(var  j= 0; j < bProps.length; j++){
     let arr = [];
     if(aProps[i] !== bProps[j]){
       arr.push(bProps[j]); 
    }
  }
}

But it isn’t good solution then look througth some forume but didn’t found any appropiate solution.
May somebody can suggest some good artikle about it?


#2

You’re not supposed to be making an array, you’re supposed to be adding to the first object. What you’ve done will actually work with some tweaking, but you’re not adding anything to to the first object, you’re just making an array of keys.


#3

Maybe I’m thinking wrongly, but how I can add to obj1 property from obj2 if I don’t know which property exist and which not in obj1?
For this purpose I’m trying to compare Object.keys(obj1) with Object.keys(obj2) and if I don’t have the same property in obj1 as in obj2 then I will add this property to obj1… And for this I’m trying to compare keys array.
Maybe you could suggest how to solve it?


#4

Right, that’s fine. But you aren’t trying to create an array here. Also you are looking for keys that are in object 2 but not in 1, so you want to swap the loops and the order of the condition.

If that condition is true, then just set that key and value on object 1. obj1[key] = obj2[key]