簡體   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