Get index of array of objects via jquery

二次信任 提交于 2019-12-01 00:43:31

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.

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

Demo

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
   }
});
Andrii Skreka
Object.keys(yourObject).indexOf(yourValue);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!