我有一个三维深度的多维物体。我正在尝试如果第3级对象具有给定值。我想到的是循环遍历每个级别并使用(Object.values(obj).indexOf('red') > -1)
进行检查,但据我所知,循环是一种缓慢的方式。
例如,在下面的对象中,检查任何最内部值是否具有red
值的最快方法是什么,返回一个布尔值?
myObj: {
user1: {
apples: {
1: "red",
2: "green",
3: "black"
},
cherry: {
2: "green"
4: "dark"
}
},
user2: {
orange: {
1: "orange"
}
}
}
答案 0 :(得分:3)
这是一种递归方法,使用Oject.values()
和Array.some()
来检查对象中是否存在值:
const obj = {"user1":{"apples":{"1":"red","2":"green","3":"black"},"cherry":{"2":"green","4":"dark"}},"user2":{"orange":{"1":"orange"}}};
const findValue = (o, val) => Object.values(o)
.some((v) => v && typeof(v) === 'object' ? findValue(v, val) : (v === val));
console.log(findValue(obj, 'red'));
console.log(findValue(obj, 'gold'));

答案 1 :(得分:3)
您可以使用depth-first search并查找嵌套对象。
function contains(object, value) {
return Object.values(object).some(
v => v && typeof v === 'object'
? contains(v, value) :
v === value
);
}
var myObj = { user1: { apples: { 1: "red", 2: "green", 3: "black" }, cherry: { 2: "green", 4: "dark" } }, user2: { orange: { 1: "orange" } } };
console.log(contains(myObj, 'red'));
console.log(contains(myObj, 42));

另一个解决方案可能是使用堆栈执行线性搜索而不会丢失。
这适用于breadth-first-search。
function contains(object, value) {
var stack = Object.values(object),
v;
while (stack.length) {
v = stack.shift();
if (v && typeof v === 'object') {
stack.push(...Object.values(v));
continue;
}
if (v === value) {
return true;
}
}
return false;
}
var myObj = { user1: { apples: { 1: "red", 2: "green", 3: "black" }, cherry: { 2: "green", 4: "dark" } }, user2: { orange: { 1: "orange" } } };
console.log(contains(myObj, 'red'));
console.log(contains(myObj, 42));

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:1)
使用递归深度优先函数迭代键,然后在最深层,返回true
。一个“问题”是确保字符串在迭代时不返回单个字符串,因为这只会无限地递归。
function hasKey(object, depth = 0) {
if (depth === 0) {
return true;
}
for (const key in Object(object)) {
const value = object[key];
// prevent nested checks of characters in strings
if (typeof value !== 'string' || value.length !== 1 || typeof object !== 'string') {
if (hasKey(value, depth - 1)) {
return true;
}
}
}
return false;
}
let myObj = {"user1":{"apples":{"1":"red","2":"green","3":"black"},"cherry":{"2":"green","4":"dark"}},"user2":{"orange":{"1":"orange"}}};
// has keys at depth 3
console.log(hasKey(myObj, 3));
// does not have keys at depth 4
console.log(hasKey(myObj, 4));
虽然这个答案在行数中可能更长,但它确实在每个深度迭代键而不是将所有Object.values()
缓冲到每个深度的数组中,这在技术上会使其他答案无法声明一种“深度优先”的方法,因为缓冲会导致“广度优先”的行为。