如何递归检查嵌套对象中是否存在值

问题描述 投票:0回答:1

无法创建完全递归函数来检查嵌套对象中是否存在值

尝试在 JavaScript(ES6+) 中实现代码,但只能使用 for 循环半递归地一次检查 key 的内容

function contains(obj, value) {
  for (var key in obj) {
    if (typeof obj[key] === "object") {
      return contains(obj[key], value);
    }

    if (obj[key] === value) {
      return true;
    }
  }
  return false;
}
javascript algorithm object
1个回答
0
投票

您的示例非常缺乏...但我会尽力帮助您提供可用的信息...

如果您想验证并且只是验证一个对象是否具有某个值作为其可枚举属性值之一,那么您可以这样做:

Object.values(Object(obj)).includes(val);

注意

Object.values()
仅返回可枚举属性值的数组。如果您还希望验证不可枚举属性,那么您可以执行以下操作:

function Contains ( Subject, Value, Hidden = true )
{
   let Current = Object(Subject);
   
   do
   {
      for ( const Property of ( Hidden ? Reflect.ownKeys(Current) : Object.keys(Current) ) )
      {
         if ( Object.is(Value, Current[Property]) )
         {
            return true;
         }
      }
      
      Current = Object.getPrototypeOf(Current);
   }
   while ( Current !== null );
   
   return false;
}

// Simple object
var Obj1 = { AnyProperty: 3 };

console.log( 'Obj1 =', Obj1 );
console.log( '3?', Contains(Obj1, 3) ); // outputs: 3? true
console.log( '2?', Contains(Obj1, 2) ); // outputs: 2? false

// Simple object with non enumerable property
var Obj2 = { [ Symbol('Non Enumerable Property') ]: 5 };

console.log( 'Obj2 =', Obj2 );
console.log( '5?', Contains(Obj2, 5) ); // outputs: 5? true
console.log( '4?', Contains(Obj2, 4) ); // outputs: 4? false
console.log( '3?', Contains(Obj2, 3) ); // outputs: 3? false
console.log( '2?', Contains(Obj2, 2) ); // outputs: 2? false
// Obj2 didn't inherit Obj1 in the code above.

// But now Obj2 inherits Obj1.
Object.setPrototypeOf(Obj2, Obj1);

// Obj3 inherits Obj2 that inherits Obj1.
var Obj3 = Object.create(Obj2);

console.log( 'Obj3 =', Obj3 );
console.log( '5?', Contains(Obj3, 5) ); // outputs: 5? true
console.log( '4?', Contains(Obj3, 4) ); // outputs: 4? false
console.log( '3?', Contains(Obj3, 3) ); // outputs: 3? true
console.log( '2?', Contains(Obj3, 2) ); // outputs: 2? false

// Obj4 contains Obj1, Obj2 and itself.
var Obj4 = { Obj1, Obj2, get Self () { return Obj4; } };

console.log( 'Obj4 =', Obj4 );
console.log( 'Obj1?', Contains(Obj4, Obj1) ); // outputs: Obj1? true
console.log( 'Obj2?', Contains(Obj4, Obj2) ); // outputs: Obj2? true
console.log( 'Obj3?', Contains(Obj4, Obj3) ); // outputs: Obj3? false
console.log( 'Obj4?', Contains(Obj4, Obj4) ); // outputs: Obj4? true

注意:我添加了一个

Hidden
参数,默认值为
true
。这意味着,如果您不指定
false
作为第三个参数,它将验证所有属性,包括那些不可枚举的属性。您可以通过将默认值更改为
false
来反转此行为。

© www.soinside.com 2019 - 2024. All rights reserved.