-1
const dontPickFrom = ['item3', 'item4'];

const data = {'item1': 1, 'item2': 2, 'item3': 3, 'item4': 4, 'item5': 5};

I have this above data and would like to get rid of the item3 and item4 without using delete. So, the end product would be {'item1': 1, 'item2': 2, 'item5': 5}. I did it below but it's not outputting the result that i want.

removeSomeValues() {
  return Object.keys(data).reduce((acc, key) => {
      if (!dontPickFrom.includes(key)) {
        return {...acc, [key]: data[key]};
      }
    }, {})
}
sfasfasd
  • 97
  • 1
  • 5
  • The problem, is that you are only returning the accumulator when entering the `if` conditon. Also, why `data` and `dontPickFrom` aren't arguments of the function `removeSomeValues()`? And also appears you have missed `function` keyword before `removeSomeValues()` – Shidersz Aug 07 '19 at 15:26
  • This could be so much cleaner if there was better support for `fromEntries` – epascarello Aug 07 '19 at 15:34
  • Related: https://stackoverflow.com/questions/38750705/filter-object-properties-by-key-in-es6 – Shidersz Aug 07 '19 at 15:43

4 Answers4

2

You need an else branch:

   if (!dontPickFrom.includes(key)) {
    return {...acc, [key]: data[key]};
  } else return acc; // <<<
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

var dontPickFrom = ['item3', 'item4'];

var data = {
  'item1': 1,
  'item2': 2,
  'item3': 3,
  'item4': 4,
  'item5': 5
};


for (let item in data) {
  if (dontPickFrom.includes(item)) {
    data[item] = undefined;
  }
}

console.log(JSON.stringify(data));
Pheonix
  • 69
  • 1
  • 8
0

Problem is you only return in one place so when it is there, you return undefined.

removeSomeValues() {
  return Object
           .keys(data)
             .reduce((acc, key) => 
               dontPickFrom.includes(key)
                 ? acc
                 : {...acc, [key]: data[key]}
}

Not all js engines support formEntries just yet, but if you are using one that does it can be written as

const filteredObj = Object.fromEntries(Object.entries(data).filter(([key]) => !dontPickFrom.includes(key)))
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

What about filtering them out first?

return Object.keys(data)
  .filter(key => !dontPickFrom.includes(key))
  .reduce((acc, key) => ({...acc, [key]: data[key]}), {});
Ricola
  • 2,621
  • 12
  • 22