简体   繁体   English

通过属性值查找对象属性的索引

[英]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. 使用Javascript,我试图获取共享单击按钮值的对象属性的索引。 I know the object's index to search, counter , but need to get the object property and it's index. 我知道要搜索的对象的索引counter ,但是需要获取对象的属性及其索引。 For example, if I click the button with a value of "Poised", I need to return index of 'item2', which is 1. 例如,如果单击具有“平衡”值的按钮,则需要返回“ item2”的索引,即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. 正如@obermillerk所说,JavaScript对象没有索引。 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. 但是您可以使用Object.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); 

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

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