DEV Community


Posted on

How to remove the falsy value attribute from object

Alt Text

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;
Enter fullscreen mode Exit fullscreen mode

assume my object like this

const myObject = {
  withValue: "have some value",
  withNumber: 1234,
  nullValue: null,
  undefinedValue: undefined,
  emptyValue: "",
  falseValue: false
Enter fullscreen mode Exit fullscreen mode

and want to return those attribute which has actual value.

// output: Object { withValue: "have some value", withNumber: 1234 }
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

shihababrar profile image
Shihab Abrar Hossain • Edited

Try this:

let output = Object.entries(myObject).reduce((a,[k,v]) => (v == null ? a : (a[k]=v, a)), {});