Javascript按值查找嵌套对象

时间:2019-11-21 23:30:12

标签: javascript pojo

问题摘要

我仍在学习Javascript,我知道这可能很基本,但遇到了一些麻烦。

我有一个包含嵌套对象的对象,我需要检查是否有任何嵌套对象具有与特定值匹配的属性。

代码

我想检查下面的对象以查看const eSportsUsername =“ Dark”是否存在并返回一个布尔值。


Const object = {
   Dark: {_id: "5da78b305f0cc7fc44417821", online: false, eSportsUsername: "Dark"},
   HighDistortion: {_id: "5da78b505f0cc7fc44417825", online: false, eSportsUsername: "HighDistortion"}
}

有人可以推荐如何实现这一目标吗?

3 个答案:

答案 0 :(得分:1)

您有两个选择来获取值。  根据示例的点符号  或括号符号

const object = {
   Dark: {_id: "5da78b305f0cc7fc44417821", online: false, eSportsUsername: "Dark"},
   HighDistortion: {_id: "5da78b505f0cc7fc44417825", online: false, eSportsUsername: "HighDistortion"}
}

console.log(object['Dark']['eSportsUsername']);
//or
console.log(object.Dark.eSportsUsername);

//to return a boolean 
 let boolean = '';
if(object.Dark.eSportsUsername == "Dark")
{
boolean =  true;

}else {
boolean = false;
}

console.log(boolean);

答案 1 :(得分:1)

答案

Object.values(object).some(obj => obj.eSportsUsername === "Dark") // will return true if any of the nested object has property with "Dark"

说明

为此,您应该

  • 首先:将对象转换为属性值数组
  • 秒:遍历数组以检查元素是否具有{eSportsUsername:“ Dark”}

第一步是使用Object.values()。在您的示例中,Object.values(object)将返回

[{eSportsUsername: "Dark", online: false}, {eSportsUsername:"HighDistortion", online: false}]

第二步,我们可以使用Array.prototype.some()迭代数组,并检查是否有任何嵌套对象的eSportsUsername值为"Dark"

答案 2 :(得分:0)

使用递归来匹配嵌套对象中的值。无论有没有密钥,这都可以使用。

如果您想要不递归的解决方案,请发表评论

参考: Array.prototype.entiresArray .prototype.some

const input = {
  Dark: {
    _id: "5da78b305f0cc7fc44417821",
    online: false,
    eSportsUsername: "Dark"
  },
  HighDistortion: {
    _id: "5da78b505f0cc7fc44417825",
    online: false,
    eSportsUsername: "HighDistortion"
  }
};

const isExist = (obj, val, key) => Object.entries(obj)
  .some(([k, v]) => {
    if (v instanceof Object) { 
      // [] instanceof Object -> true
      // {} instanceof Object -> true
      // "abc" instanceof Object -> false
      // 123 instanceof Object -> false
      // null instanceof Object -> false
      // undefined instanceof Object -> false
      
      return isExist(v, val, key);
    }

    const keyMatched = !key || k === key;

    return keyMatched && (v === val);
  });


console.log(isExist(input, 'Dark', 'eSportsUsername'));
console.log(isExist(input, 'HighDistortion', 'eSportsUsername'));
console.log(isExist(input, 'Dark', 'unknown'));
console.log(isExist(input, '5da78b305f0cc7fc44417821'));