繁体   English   中英

Nodejs - 如何在两个条件下找到索引,一个条件是属性存在的地方

[英]Nodejs - How to find the index with two conditions, one condition being where a property exists

我有一个看起来像这样的对象:

{
   "examples":[
      {
         "key":"value1"
      },
      {
         "key":"value1",
         "key2":"example"
      },
      {
         "key":"value1"
      },
      {
         "key":"value2"
      },
      {
         "key":"value2",
         "key2":"example"
      },
      {
         "key":"value2"
      }
   ]
}

我正在尝试使用 findIndex 来查找对象中key === 'value1'key2存在的位置(因此在这种情况下,索引将为 1)。 我试过使用类似var x = examples.findIndex(({key}) => key === 'value1' && ({key2}) => key2)但它不起作用。 我该怎么做? 任何答案将不胜感激! :)

examples是数据对象的一个​​属性,因此您需要遍历该数组。 examples.findIndex不会做任何事情。

然后,您可以检查key是否具有“value1”作为值,并且对象中是否有key2

 const data={examples:[{key:"value1"},{key:"value1",key2:"example"},{key:"value1"},{key:"value2"},{key:"value2",key2:"example"},{key:"value2"}]}; const result = data.examples.findIndex(obj => { return obj.key === 'value1' && obj.key2; }); console.log(result);

暂无
暂无

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

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