Sometimes we want to remove null, empty, undefined, false value attribute from an object. we can do this using the below method.
const removeFalsyElement = object => { const newObject = {}; Object.keys(object).forEach(key => { if (object[key]) { newObject[key] = object[key]; } }); return newObject; };
assume my object like this
const myObject = { withValue: "have some value", withNumber: 1234, nullValue: null, undefinedValue: undefined, emptyValue: "", falseValue: false };
and want to return those attribute which has actual value.
usage
console.log(removeFalsyElement(myObject)); // output: Object { withValue: "have some value", withNumber: 1234 }
Top comments (2)
Try this:
let output = Object.entries(myObject).reduce((a,[k,v]) => (v == null ? a : (a[k]=v, a)), {});
console.log(output)