简体   繁体   中英

Find object property's index by property's value

Using Javascript, I am trying to get the index of the object property who shares the value of a clicked button. I know the object's index to search, counter , but need to get the object property and it's index. For example, if I click the button with a value of "Poised", I need to return index of 'item2', which is 1.

 var questions = [{ 'item1': 'Alert', 'item2': 'Poised', 'item3': 'Ready', 'item4': 'Eager' }, { 'item1': 'Patient', 'item2': 'Diligent', 'item3': 'Forceful', 'item4': 'Prepared' } ] counter = 0 buttonValue = "Poised" console.log(questions[counter]) 

How can I do this?

As @obermillerk said, JavaScript objects do not have indexes. but you can use Object.values() to get the index from the array which basically includes the values of that object, by the order of its values.

 var questions = [{ 'item1': 'Alert', 'item2': 'Poised', 'item3': 'Ready', 'item4': 'Eager' }, { 'item1': 'Patient', 'item2': 'Diligent', 'item3': 'Forceful', 'item4': 'Prepared' } ]; var index; questions.forEach(obj => { var value = Object.values(obj).indexOf('Poised'); if(value !== -1) { index = value; } }) console.log(index); 

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