0

I have an object named x. It looks similar to this:

{
  a: 123,
  b: null,
  c: [1, 2, 3]
}

I want to get the names of all the keys that are truthy, so I need to get an array that looks something like ["a", "c"], because x.a and x.c are truthy, but x.b is not. How can I do this?

shreyasm-dev
  • 2,711
  • 5
  • 16
  • 34

1 Answers1

1

You can do this using Object.keys and Array.prototype.filter.

var x = {
  a: 123,
  b: null,
  c: [1, 2, 3]
}

var y = Object.keys(x).filter(item => !!x[item])
console.log(y)

The !! operator, quoting this answer:

Converts Object to boolean. If it was falsey (e.g. 0, null, undefined, etc.), it will be false, otherwise, true.

So, assuming truthyValue is truthy and falsyValue is falsy, !!truthyValue will always be true, and !!falseyValue will always be false.

shreyasm-dev
  • 2,711
  • 5
  • 16
  • 34