通过jquery获取对象数组的索引 [英] Get index of array of objects via jquery
问题描述
我有以下数组:
var = array[
{"id" : "aa", "description" : "some description"},
{"id" : "bb", "description" : "some more description"},
{"id" : "cc", "description" : "a lot of description"}]
我试图找到包含的数组的索引 id ===bb
。我想出的解决方案如下:
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
是否更容易具有跨浏览器功能的方式?我尝试了 $。inArray(id,array)
但它不起作用。
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
注意:这应该是交叉的浏览器兼容,并且也可能比任何JQuery替代方案更快。
NOTE: This should be cross browser compatible, and will also likely be faster than any JQuery alternative.
这篇关于通过jquery获取对象数组的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!