Skip to content
Advertisement

Check for non null array during filtering an object

Trying to filter the object to return only non null values.

Below is excerpt from my code. How do I check for non null values in the array job in this case?

const name = null,
  age = '25',
  job = [null];

const obj = {
  name,
  age,
  job
};

const result = Object.fromEntries(
  Object.entries(obj).filter(([_, value]) => value)
);

console.log(result)

Could anyone please help?

I was expecting the result to be

{
  "age": "25"
}

Advertisement

Answer

First map the array in the entries to keep only truthy values, then filter the entries by whether the entry is truthy and not a 0-length array:

const name = null,
  age = '25',
  job = [null];

const obj = {
  name,
  age,
  job
};

const result = Object.fromEntries(
  Object.entries(obj)
    .map(
      ([key, value]) => [key, Array.isArray(value) ? value.filter(v => v) : value]
    )
    .filter(([, value]) => value && (!Array.isArray(value) || value.length))
);

console.log(result)
Advertisement