简体   繁体   English

如何遍历嵌套对象以检查是否找到true?

[英]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. 我有一个嵌套的对象,我想遍历一个特定的属性并检查true是否存在。

If true isn't found I want to return false, otherwise if there is one instance of true I want to stop the loop. 如果找不到true,我想返回false,否则,如果有一个true实例,我想停止循环。

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 我只想遍历objectProperty,如果找到true,则返回true,如果找不到true,则返回false

Check if any of the values is true inside the object. 检查对象中的任何值是否为true。

 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. 您可以使用Object.keys(obj)方法获得该方法,该方法将返回给定对象的键数组。 Next, you might simply iterate and check or use a lambda function, in our case, reduce. 接下来,您可以简单地迭代并检查或使用lambda函数(在我们的示例中为reduce)。 Node that you iterate through an array of keys, so you have to check obj[key] for a particular value. 您遍历键数组的节点,因此必须检查obj[key]的特定值。

I added a jsfiddle with two working examples below. 我在下面添加了两个工作示例的jsfiddle。

 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! 干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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