简体   繁体   中英

How do I loop through a nested object to check if true is found?

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

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) 

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM