0

I have a nested object, I want to loop through a particular property and check if true exists.

If true isn't found I want to return false, otherwise if there is one instance of true I want to stop the loop.

let object = {
    firstProperty: 'foo',
    secondProperty: 'bar',
    objectProperty: {
        value1: false,
        value2: false,
        value3: true
}

I only want to loop through the objectProperty, and return true if true is found, and false if true is NOT found

  • Possible duplicate of [How to iterate over a JavaScript object?](https://stackoverflow.com/questions/14379274/how-to-iterate-over-a-javascript-object) – Drew Reese Jan 12 '19 at 05:53

2 Answers2

2

Check if any of the values is true inside the object.

let object = {
    firstProperty: 'foo',
    secondProperty: 'bar',
    objectProperty: {
        value1: false,
        value2: false,
        value3: true
    }
}


const res = Object.values(object.objectProperty).some(value => value === true)

console.log(res)
Daniel Doblado
  • 2,481
  • 1
  • 16
  • 24
0

Well, once you get the keys array, everything is simple. You can get that using Object.keys(obj) method, that will return an array of keys of the given object. Next, you might simply iterate and check or use a lambda function, in our case, reduce. Node that you iterate through an array of keys, so you have to check obj[key] for a particular value.

I added a jsfiddle with two working examples below.

let obj = {
    firstProperty: 'foo',
    secondProperty: 'bar',
    objectProperty: {
        value1: false,
        value2: false,
        value3: true
    }
};

// Method 1
let inner = obj.objectProperty;
let ans = Object.keys(inner).reduce((a, e) => inner[e] || a, false);
console.log(ans);

// Method 2
let found = false;
Object.keys(inner).forEach(key => {
  if (inner[key])
    found = true;
});

console.log(found);

Cheers!

Adrian Pop
  • 1,879
  • 5
  • 28
  • 40