简体   繁体   English

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

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

I have an object that looks like this:我有一个看起来像这样的对象:

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

I'm trying to use findIndex to find where in the object that key === 'value1' and key2 exists (so in this instance the index would be 1).我正在尝试使用 findIndex 来查找对象中key === 'value1'key2存在的位置(因此在这种情况下,索引将为 1)。 I've tried using something like var x = examples.findIndex(({key}) => key === 'value1' && ({key2}) => key2) but it's not working.我试过使用类似var x = examples.findIndex(({key}) => key === 'value1' && ({key2}) => key2)但它不起作用。 How do I go about this?我该怎么做? Any answers would be greatly appreciated!任何答案将不胜感激! :) :)

examples is a property of the data object, so you need to iterate over that array. examples是数据对象的一个​​属性,因此您需要遍历该数组。 examples.findIndex won't do anything. examples.findIndex不会做任何事情。

You can then check to see if key has "value1" as a value, and that there is a key2 in the object.然后,您可以检查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