I have the following array:
var = array[
{"id" : "aa", "description" : "some description"},
{"id" : "bb", "description" : "some more description"},
{"id" : "cc", "description" : "a lot of description"}]
and I try to find the index of the array that contains the id === "bb"
. The solution I came up with is the following:
var i = 0;
while(array[i].id != "bb"){
i++;
}
alert(i) //returns 1
Is there an easier way that has cross-browser functionality? I tried $.inArray(id,array)
but it doesn't work.
I don't see any problem with the complexity of your code, but I would recommend a couple of changes including adding some validation in case the value does not exists. Further more you can wrap it all in a reusable helper function...
function getArrayIndexForKey(arr, key, val){
for(var i = 0; i < arr.length; i++){
if(arr[i][key] == val)
return i;
}
return -1;
}
This can then be used in your example like so:
var index = getArrayIndexForKey(array, "id", "bb");
//index will be -1 if the "bb" is not found
NOTE: This should be cross browser compatible, and will also likely be faster than any JQuery alternative.
var myArray = [your array];
var i = 0;
$.each(myArray, function(){
if (this.id === 'bb') return false;
i++;
})
console.log(i) // will log '1'
Update with modern JS.
let index
myArray.map(function(item, i){
if (item.id === 'cc') index = i
})
console.log(index) // will log '2'
inArray can't work with multidimensional array so try like the following
var globalarray= [
{"id" : "aa", "description" : "some description1"},
{"id" : "bb", "description" : "some more description"},
{"id" : "cc", "description" : "a lot of description"}];
var theIndex = -1;
for (var i = 0; i < globalarray.length; i++) {
if (globalarray[i].id == 'bb') {
theIndex = i;
break;
}
}
alert(theIndex);
You can use jQuery.each - http://api.jquery.com/jQuery.each/
var i;
jQuery.each(array, function(index, value){
if(value.id == 'bb'){
i = index;
return false; // retrun false to stop the loops
}
});
Object.keys(yourObject).indexOf(yourValue);
来源:https://stackoverflow.com/questions/19111224/get-index-of-array-of-objects-via-jquery