0

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 }
};
boscode
  • 79
  • 6
  • Use bracket notation instead of dot notation to look up a variable property name – CertainPerformance Nov 23 '20 at 15:20
  • that still only returns object2 as { a: 'string' } in the above code. – boscode Nov 23 '20 at 15:28
  • You also need to either remove the `typeof`, or use `=== 'undefined'`, since `typeof` resolves to a string, never to `undefined` – CertainPerformance Nov 23 '20 at 15:29
  • thanks for your patience. I actually tried that earlier, and tests come through except for a fail on "ignore the object prototype". Any tips or explanation for this? – boscode Nov 23 '20 at 15:34
  • Use `hasOwnProperty` to check to see if the *instance object* has the property - it'll ignore inherited properties. As an inelegant shorthand, you could also spread the object first before continuing with the code. – CertainPerformance Nov 23 '20 at 15:38
  • I'm struggling to see where to implement that to make the code work as intended – boscode Nov 23 '20 at 15:52
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/224993/discussion-between-mathias-sode-and-certainperformance). – boscode Nov 23 '20 at 15:54

1 Answers1

2

(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));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320