Recently while working I came across a scenario. I had to find index of a particular item on given condition from a JavaScript object array. In this post we will see how to find index of object from JavaScript array of object.
Let us assume we have a JavaScript array as following,
var studentsArray =[
{ "rollnumber": 1,"name": "dj","subject": "physics"},
{"rollnumber": 2,"name": "krishna","subject": "biology"},
{"rollnumber": 3,"name": "amit","subject": "chemistry"}, ];
Now if we have a requirement to select a particular object in the array. Let us assume that we want to find index of student with name Tanmay.
We can do that by iterating through the array and comparing value at the given key.
We can do that by iterating through the array and comparing value at the given key.
function functiontofindIndexByKeyValue(arraytosearch, key, valuetosearch) {
for (var i = 0; i < arraytosearch.length; i++) {
if (arraytosearch[i][key] == valuetosearch) {
return i;
}
}
return null;
}
for (var i = 0; i < arraytosearch.length; i++) {
if (arraytosearch[i][key] == valuetosearch) {
return i;
}
}
return null;
}
You can use the function to find index of a particular element as below,
var index = functiontofindIndexByKeyValue(studentsArray, "name", "krishna");
alert(index);
In this way you can find index of an element in JavaScript array of object. I hope you find this quick post useful. Thanks for reading.
var index = functiontofindIndexByKeyValue(studentsArray, "name", "krishna");
alert(index);
In this way you can find index of an element in JavaScript array of object. I hope you find this quick post useful. Thanks for reading.
Comments
Post a Comment