繁体   English   中英

查找对象是否具有值的最快方法是什么(多维对象)

[英]What is the fastest way of finding if object has a value (multidimensional object)

我有一个三维深度的多维物体。 我正在尝试如果第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"
     }
   }
}

这是一个递归方法,它使用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')); 

您可以使用深度优先搜索并查找嵌套对象。

 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)); 

另一种解决方案可以是使用堆栈并执行线性搜索而无需重复。

这可以作为广度优先搜索

 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; } 

使用递归深度优先函数迭代键,然后在最深层,返回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()缓冲到每个深度的数组中,这在技术上取消了其他答案能够声称“深度”的资格 - 第一个“方法,因为缓冲导致”广度优先“行为。

暂无
暂无

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

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