简体   繁体   中英

Javascript How to find the index of an object, of an array of dictionaries, by a given key and value

I have an array of dictionaries, where each object has the same keys but different values, like:

var arrayOfDicts = {};

Object 0: 'key1' : 'valueA'
          'key2' : 'valueB'
          'key3' : 'valueC'

Object 1: 'key1' : 'valueD'
          'key2' : 'valueE'
          'key3' : 'valueF' 

How can I get the object index for a given key and value without doing a for loop? For example, the object index where 'key2' = 'valueE' will return 1.

If you are not building a function that accepts a query expression, Array.findIndex should be sufficient.

 const arr = [{ 'key1': 'valueA', 'key2': 'valueB', 'key3': 'valueC' }, { 'key1': 'valueD', 'key2': 'valueE', 'key3': 'valueF' } ] const idx = arr.findIndex(({ key2 }) => key2 === 'valueE'); console.log(idx)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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