Felix Dombek
Felix Dombek

Reputation: 14382

Test if all leaf properties in a nested object are true

Is there a way (without writing a recursive function manually) to test if all leaf properties in an object are true?

obj = { a: true, b: { c: true } }

If it was an array, I could _.flattenDeep(obj).values().every(_.identity), but it is an object.

There are only boolean leaf properties in the object.

Upvotes: 0

Views: 553

Answers (1)

baao
baao

Reputation: 73301

I don't think that this is possible. If you flatten an object, you'll override duplicate keys which will render the whole operation senseless. A very simple recursive function can check it though

function allTrue(obj) {
  return Object.values(obj)
    .every(v => v instanceof Object ? allTrue(v) : v === true)
}

let obj = {
  a: true,
  b: {
    c: true
  }
};
console.log(allTrue(obj));

Upvotes: 3

Related Questions