通过jquery获取对象数组的索引

时间:2013-10-01 08:17:51

标签: javascript jquery indexing utility

我有以下数组:

var = array[
            {"id" : "aa", "description" : "some description"},
            {"id" : "bb", "description" : "some more description"},
            {"id" : "cc", "description" : "a lot of description"}]

我试图找到包含id === "bb"的数组的索引。我想出的解决方案如下:

var i = 0;
while(array[i].id != "bb"){
   i++;
}
alert(i) //returns 1

是否有更简单的跨浏览器功能?我试过$.inArray(id,array),但它不起作用。

5 个答案:

答案 0 :(得分:5)

我没有看到代码复杂性有任何问题,但我建议进行一些更改,包括在值不存在的情况下添加一些验证。您还可以将其全部包装在可重用的辅助函数中......

function getArrayIndexForKey(arr, key, val){
    for(var i = 0; i < arr.length; i++){
        if(arr[i][key] == val)
            return i;
    }
    return -1;
}

然后可以在您的示例中使用它,如下所示:

var index = getArrayIndexForKey(array, "id", "bb");
//index will be -1 if the "bb" is not found

Here is a working example

注意:这应该是跨浏览器兼容的,并且也可能比任何JQuery替代方案更快。

答案 1 :(得分:2)

var myArray = [your array];
var i = 0;

$.each(myArray, function(){
    if (this.id === 'bb') return false;
    i++;
})

console.log(i) // will log '1'

使用现代JS进行更新。

let index
myArray.map(function(item, i){
    if (item.id === 'cc') index = i
})

console.log(index) // will log '2'

答案 2 :(得分:1)

inArray无法使用多维数组,请尝试以下

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

答案 3 :(得分:0)

您可以使用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
   }
});

答案 4 :(得分:0)

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