How to remove falsy values (false, 0, "", null, NaN, undefined) from an object in Node.js

1 Answer

0 votes
const obj = {
  a: undefined,
  b: null,
  c: 'nodejs',
  d: NaN,
  e: 927398,
  f: false,
  g: true,
  h: 'python'
};

Object.keys(obj).forEach(key => {
    if (!obj[key]) {
        delete obj[key];
    }
});

console.log(obj);

 
   
     
     
/*
run:
     
{ c: 'nodejs', e: 927398, g: true, h: 'python' }
     
*/

 



answered May 8, 2022 by avibootz
...