0

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"
}
7
  • 3
    Arrays are truthy. Pop open your developer console and type !![]. And even if empty arrays were falsy, yours is not empty Commented Dec 18, 2020 at 23:26
  • 4
    You will have to check typeof for each value and if it is an array then traverse through the array and check. Commented Dec 18, 2020 at 23:27
  • Also, what about scenarios where an array has mixed values, i.e. ['developer', null]? Would you want to reject that array or keep it? Commented Dec 18, 2020 at 23:28
  • I will have only single value like ['developer'] @Terry Commented Dec 18, 2020 at 23:29
  • 1
    Less smelly, if it is expected only ever be one single value, the usage of an array is unnecessary Commented Dec 18, 2020 at 23:39

3 Answers 3

2

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)

Sign up to request clarification or add additional context in comments.

Comments

0

If your arrays can only have one element, you can check if the value[0] is truthy as well.

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

const obj = {
  name,
  age,
  job
};

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

console.log(result)

Comments

0

This can be done as follows:

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

const obj = {
  name,
  age,
  job
};
let result = {
}
for (prop in obj) {
  if (obj[prop]) {
    if (Array.isArray(obj[prop])) {
      result[prop] = obj[prop].filter(function (element) {
        return element != null;
      })
    }
    else {
      result[prop] = obj[prop];
    }
  }
}

console.log(result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.