Reputation: 627
function extend(obj1, obj2) {
var obj2Keys = Object.keys(obj2);
var obj2Values = Object.values(obj2);
var obj1Keys = Object.keys(obj1);
var obj1Values = Object.keys(obj1);
var newObj = {};
for(var i=0; i<obj1Keys.length; i++) {
if(obj1Keys[i] !== obj2Keys[i]) {
}
}
}
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}
/*
1. Add any keys that are not in the 1st object.
2. If the 1st object already has a given key, ignore it (do not
overwrite the property value).
3. Do not modify the 2nd object at all.
*/
Hey guys, trying to figure this one out. I'm sure i'm doing this the most inefficient way. I'm struggling to compare indexes of these objects.. Any help?? I was using for in loops originally but I couldn't conceptually understand what I was doing lol. Kinda stuck at this point.
Upvotes: 2
Views: 1319
Reputation: 12218
Use the spread syntax to combine the objects. The spread syntax basically inserts the objects key/value pairs wherever you write it, so you're creating a new object with {...obj1, ...obj2}
. If there are pairs with duplicate keys, the pair from the second object will be selected.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
let obj1 = {a: 1, b: 2}
let obj2 = {b: 4, c: 3}
let obj3 = {...obj2, ...obj1}
console.log(obj3)
Upvotes: 1
Reputation: 1271
const firstObject = {a:1,b:2,c:3}
const secondObject = {a:11,b:22,c:33,d:44}
var newObject = {...secondObject,...firstObject}
console.log(newObject)
result:
{"a":1,"b":2,"c":3,"d":44}
Upvotes: 3
Reputation: 28424
keys
of obj2
for-loop
obj1
does not have this key
, and the record to it from obj2
function extend (obj1, obj2) {
const obj2Keys = Object.keys(obj2);
for(let i = 0; i < obj2Keys.length; i++) {
const currentKey = obj2Keys[i]
if(!obj1[currentKey]) {
obj1[currentKey] = obj2[currentKey];
}
}
}
const obj1 = { a: 1, b: 2 }; const obj2 = { b: 4, c: 3 };
extend(obj1, obj2);
console.log(obj1); // --> {a: 1, b: 2, c: 3}
console.log(obj2); // --> {b: 4, c: 3}
Another way using .forEach
:
function extend (obj1, obj2) {
Object.keys(obj2).forEach(currentKey => {
if(!obj1[currentKey]) {
obj1[currentKey] = obj2[currentKey];
}
});
}
const obj1 = { a: 1, b: 2 }; const obj2 = { b: 4, c: 3 };
extend(obj1, obj2);
console.log(obj1); // --> {a: 1, b: 2, c: 3}
console.log(obj2); // --> {b: 4, c: 3}
Upvotes: 1