0

Is there a nicer way (for example with filter) to remove values from object than this?

const filters = {
   a: null,
   b: 0,
   c: 'xxx',
   d: 'abc',
}

const MY_FALSY = [undefined, '', null];
const newFilters = Object.entries(filters).reduce(
  (a, [k, v]) =>
    MY_FALSY.indexOf(v) > -1 ? a : { ...a, [k]: v },
  {}
);

Is there a better way to do it? I tried to use filter but I had to use delete which as I know we should avoid.

NOTE: I don't want to use any libraries like underscore.js

Outcome:

{
   b: 0,
   c: 'xxx',
   d: 'abc',
}
heisenberg7584
  • 563
  • 2
  • 10
  • 30

1 Answers1

1
const removeFalsy = (myObject)=>{
  const new_obj = {...myObject};
  Object.keys(new_obj).forEach(key=> new_obj[key] || new_obj[key]===0 ? new_obj[key] : delete new_obj[key]);
  return new_obj;
}

See if this works. Here we created a pure function to copy the object, remove falsy keys and then return the new object.

Adnan Sabbir
  • 181
  • 1
  • 13
  • Nice. Incidentally your function seems to work without `const new_obj = {...myObject};` (so long as you change 'myObject' to 'new_obj' in the 1st line of course). – Frazer Nov 19 '19 at 11:31
  • 1
    In a pure function you should not do that. Our goal is to create a function that makes a copy of your object and does whatever it need to do there and return the new object. After this function if you console log both filter and the newly returned object you will see that your filter object is not changed. But the new returned object does not have any falsy value But if you want to change your existing object only Object.keys(new_obj).forEach(key=> new_obj[key] || new_obj[key]===0 ? new_obj[key] : delete new_obj[key]); only this line was enough – Adnan Sabbir Nov 19 '19 at 11:39