繁体   English   中英

你如何检查对象数组的 object 中是否存在值?

[英]How do you check if value exist in object of object's array?

我想知道我应该使用哪种逻辑来检查祖父 object 中包含的每个对象的父 object 数组

大家好,我想检查这个值是否存在,例如:“127.0.0.1”存在于这个 object 中(MyObject 中有 2k 个对象)

{
  "name" : MyObject
  "value": [
      {
        "name" : "Object1",
        "properties":{
          "address" : [
             "13.65.25.19/32",
             "13.66.60.119/32",
           ]
         }
      },
      {
        "name" : "Object2",
        "properties":{
          "address" : [
             "13.65.25.19/32",
             "127.0.0.1",
           ]
         }
      }
    ]
}

顺便说一句,include() 是否需要匹配整个字符串,或者例如,如果 127.0.0.1 在我的 object 127.0.0.1/32 中是这样的,即使有 ip 范围,我仍然可以检索它吗?

您的数据结构非常具体,因此您可以编写一个可以反复调用的自定义方法。 它将检查一个

 const obj = { name: 'MyObject', value: [ { name: 'Object1', properties: { address: ['13.65.25.19/32', '13.66.60.119/32'], }, }, { name: 'Object2', properties: { address: ['13.65.25.19/32', '127.0.0.1'], }, }, ], }; const address = '127.0.0.1'; const includesAddress = (address) => { for (const val of obj.value) { if (val.properties.address.some((a) => address === a)) return true; } return false; }; console.log(includesAddress(address));

Array.flatMap实现

 const obj = { name: 'MyObject', value: [ { name: 'Object1', properties: { address: ['13.65.25.19/32', '13.66.60.119/32'], }, }, { name: 'Object2', properties: { address: ['13.65.25.19/32', '127.0.0.1'], }, }, ], }; const address = '127.0.0.1'; const output = obj.value.flatMap(item => item.properties.address).includes(address); console.log(output);

如果你想检查部分 ip 地址是否包含在列表中,你应该使用正则表达式实现。

示例实施

 const obj = { name: 'MyObject', value: [ { name: 'Object1', properties: { address: ['13.65.25.19/32', '13.66.60.119/32'], }, }, { name: 'Object2', properties: { address: ['13.65.25.19/32', '127.0.0.1'], }, }, ], }; const address = '13.65.25.19'; const regex = new RegExp(address, 'i') const output = obj.value.flatMap(item => item.properties.address).filter(x => regex.test(x)).length > 0; console.log(output);

暂无
暂无

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

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