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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes I needed loose type check only.
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");
   }
 }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.