从具有提供的属性的特定值的对象数组中获取索引的函数 [英] Function to get index from an array of objects having certain value of provided property
问题描述
我的问题基于并类似于这个问题,但有一点不同,因为属性名称是可变的./p>
如何创建一个函数,该函数将为我返回具有所提供属性的特定值的对象的索引?
function indexOf(propertyName,lookingForValue,array){
//......
return index;
}
所以
indexOf("token",123123,[
{id_list:1, name:'Nick',token:'312312'},{id_list:2,name:'John',token:'123123'}
]);
应返回1.
我遇到的主要问题是,当我将属性名称作为字符串使用时,如何检查属性值?
function indexOf(propertyName,lookingForValue,array) {
for (var i in array) {
if (array[i][propertyName] == lookingForValue) {
return i;
}
}
return undefined;
}
请注意,我故意进行松散类型检查'==',因为您为此函数提供了一个整数,而在数组中搜索的值是一个字符串.
My question is based on and similar to this one but a little bit different because property name will be variable.
How do I create a function which will return me index of object having certain value of provided property?
function indexOf(propertyName,lookingForValue,array){
//......
return index;
}
So,
indexOf("token",123123,[
{id_list:1, name:'Nick',token:'312312'},{id_list:2,name:'John',token:'123123'}
]);
should return 1.
The main problem I have is how do I check the property value when I have the property name as string with me?
function indexOf(propertyName,lookingForValue,array) {
for (var i in array) {
if (array[i][propertyName] == lookingForValue) {
return i;
}
}
return undefined;
}
Edit: Please note that I do the loose type check '==' on purpose since you are giving an integer to this function whereas in the array the value you search for is a string.
这篇关于从具有提供的属性的特定值的对象数组中获取索引的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!