0

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?

Community
  • 1
  • 1
IsmailS
  • 10,797
  • 21
  • 82
  • 134

2 Answers2

3
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.

tyrondis
  • 3,364
  • 7
  • 32
  • 56
1

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");
   }
 }
}