Brixsta
Brixsta

Reputation: 627

Adding keys in one JavaScript Object to another only if the first object doesn't have those keys

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

Answers (3)

symlink
symlink

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

Rashid Iqbal
Rashid Iqbal

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

Majed Badawi
Majed Badawi

Reputation: 28424

  1. Get keys of obj2
  2. Iterate over them using the for-loop
  3. In each iteration, if 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

Related Questions