[英]Javascript array get all child values without knowing the parent key
I would like to validate and check if there is any existing object with true value where I don't know how to directly access all child exist value without having me to loop through the parent array. 我想验证并检查是否存在任何具有真实值的对象,而我不知道如何直接访问所有子级存在的值,而不必让我遍历父数组。 Below show the result.
下面显示结果。
{
user1: Array(2)
0: {exist: false}
1: {exist: true}
user2: Array(2)
0: {exist: false}
1: {exist: false}
}
If you know the object will only be this deep, you can use some
on Object.values()
. 如果您知道对象只会这么深,则可以在
Object.values()
上使用some
Object.values()
。 You are still looping through the arrays — there's no way to avoid that — but at least it's fairly succinct: 您仍在遍历数组-无法避免这种情况-但至少它是非常简洁的:
let obj = { user1:[ {exist: false}, {exist: false} ], user2: [ {exist: false}, {exist: true} ] } let t = Object.values(obj).some(arr => arr.some(o => o.exist === true)) // are some objects true? console.log(t)
If your objects can be arbitrarily deep, you will need to recursively look at everything. 如果您的对象可以任意深,则需要递归查看所有内容。
You cannot. 你不能。 You either query parent key, then child key, or you loop all the parent keys, then child keys.
您可以先查询父键,再查询子键,或者先循环所有父键,再查询子键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.