Get index of array of objects via jquery

倖福魔咒の 提交于 2019-12-19 04:25:46

问题


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.


回答1:


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

Here is a working example

NOTE: This should be cross browser compatible, and will also likely be faster than any JQuery alternative.




回答2:


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'



回答3:


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

Demo




回答4:


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



回答5:


Object.keys(yourObject).indexOf(yourValue);


来源:https://stackoverflow.com/questions/19111224/get-index-of-array-of-objects-via-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!