Home > Software engineering >  Is there a more concise way to only keep properties of an object depending on a 'lookup object&
Is there a more concise way to only keep properties of an object depending on a 'lookup object&

Time:09-08

If x = {a: 4, b:5, c:6, d:7} and y = {a: true, d: true}

I want to produce {a: 4, d: 7}

Note that the object y will only ever contain the fields that are to be included and the values of y will always be true (otherwise the key will not exist in the first place.

This is what I have, its a good solution (I think) but was wondering if there is anything simpler and maybe using the spread syntax ...

  const changedFields = Object.keys(y).reduce((acc, key) => {
      acc[key] = x[key];
      return acc;
    }, {});

CodePudding user response:

Your .reduce looks fine. Another option is to map the keys in y to an array of entries.

const x = {a: 4, b:5, c:6, d:7};
const y = {a: true, d: true};
const output = Object.fromEntries(
  Object.keys(y).map(key => [key, x[key]])
);
console.log(output);

CodePudding user response:

You can use Object.entries and filter

const x = {
  a: 4,
  b: 5,
  c: 6,
  d: 7
}
const y = {
  a: true,
  d: true
}


const result = Object.fromEntries(Object.entries(x).filter(([key]) => {
  return y[key]
}))

console.log(result)

Other option is to use reduce

const x = {
  a: 4,
  b: 5,
  c: 6,
  d: 7
}
const y = {
  a: true,
  d: true
}


const result = Object.keys(y).reduce((acc, key) => ({
  ...acc,
  [key]: x[key]
}), {})

console.log(result)

CodePudding user response:

also u can use reduce and hasOwnProperty

const x = {a: 4, b:5, c:6, d:7}
const y = {a: true, d: true}

const res = Object.entries(x).reduce((prev, [key, value]) => {
  if (y.hasOwnProperty(key)) {
    prev[key] = value
  }
  return prev
}, {})

console.log(res)

CodePudding user response:

Sometimes, simplest solution can be going back to for..in

const x = {a: 4, b:5, c:6, d:7};
const y = {a: true, d: true};
const changedFields = {}

for (let key in y) {
  changedFields[key] = x[key]
}
console.log(changedFields)

  • Related