Search code examples
javascriptobjectfor-in-loop

How would you check if property name(s) from one object exist in another?


I am trying to transfer/copy properties from object1 to object2, but only properties that are undefined in object2.

Thanks in advance, I hope this comes across clearly!

let object1 = { a: 1, b: 2, c: 3, d: 4 } 
let object2 = { a: 'string' }

fillObj = function (object2, object1) {
  for (let key in object1) {
    if (typeof object2.key === undefined) {
      object2[key] = object1[key];
    } 
  }
  return object2; //should return {a: 'string', b: 2, c: 3, d: 4 }
};


Solution

  • (1) Look properties on an object by a variable property name by using bracket notation, not dot notation

    (2) To check if something is undefined, either compare against undefined directly, or use typeof and compare against the string 'undefined' (but this check isn't needed for this algorithm)

    (3) Make sure the properties are own properties, not inherited properties, with hasOwnProperty

    let object1 = { a: 'string' } 
    let object2 = { a: 1, b: 2, c: 3, d: 4 }
    
    fillObj = function (object2, object1) {
      for (let key in object1) {
        if (object1.hasOwnProperty(key)) {
          object2[key] = object1[key];
        } 
      }
      return object2; //should return {a: 'string', b: 2, c: 3, d: 4 }
    };
    
    console.log(fillObj(object2, object1));

    Or use Object.entries, which iterates over own-properties only:

    let object1 = { a: 'string' } 
    let object2 = { a: 1, b: 2, c: 3, d: 4 }
    
    fillObj = function (object2, object1) {
      for (const [key, val] of Object.entries(object1)) {
        object2[key] = val;
      }
      return object2; //should return {a: 'string', b: 2, c: 3, d: 4 }
    };
    
    console.log(fillObj(object2, object1));