Similar Question:
Finding Index of an Object in JavaScript Array
In my code, I have a JavaScript array structured like this:
var userList = [
{id: "a", gender: "man", item: "stuff"},
{id: "b", gender: "woman", item: "stuff"},
{id: "c", gender: "man", item: "stuff"},
{id: "d", gender: "man", item: "stuff"}
];
I am looking for a way to utilize the indexOf method to find the index in the array based on a specific variable such as the "id".
For instance, I attempted the following:
var index = userList.indexOf("b");
userList[index].gender = "man";
Currently, I am resorting to:
for(var i=0; i<userList.length; i++) {
if(userList[i].id == "b"){
userList[i].gender = "man";
}
}
The loop method works fine, but with a large array like mine containing 150 entries and 10 items each, looping through it all is inefficient when I already know the "id" of the entry. Implementing indexOf would offer a cleaner solution if I can make it work.