Function to get index from an array of objects having certain value of provided property
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.
I make a function which can be helpful to you. Check it.
function GetindexOf(propertyName,lookingForValue,array){
var obj = array;
for(o in obj)
{
if(obj[o][propertyName] == lookingForValue)
{
//return index;
alert("You have request for "+o+" index");
}
}
}
精彩评论