Sobes.tech
Middle+

export function foo(o, arr) { return arr.reduce((a, x) => { // if (o.hasOwnProperty(x)) a[x] = o[x]; if (o[x]) a[x] = o[x]; return a; }, {}); } const obj = {a: 's'} foo(obj, ['a'])

sobes.tech AI

Answer from AI

In the function foo, an object o is filtered based on keys from the array arr. It is important to distinguish between two checks:

  • o.hasOwnProperty(x) checks whether the object has its own property named x, including properties with undefined or null values.
  • if (o[x]) checks the truthiness of the property's value, so properties with falsy values (0, false, null, undefined, '') will be ignored.

In your example:

const obj = {a: 's'};
foo(obj, ['a']); // { a: 's' }

If you replace the condition with if (o.hasOwnProperty(x)), the function will copy all properties, even if their values are falsy. This is more correct if you need to check for the presence of a property, not its value.

Example:

const obj = {a: 0, b: false, c: null};
foo(obj, ['a', 'b', 'c']);
// with hasOwnProperty: { a: 0, b: false, c: null }
// with if(o[x]): {} (because 0, false, null are falsy)

It is recommended to use hasOwnProperty to check for the existence of a property if all values are important.

export function foo(o, arr) { return arr.reduce((a… - sobes.tech