javascript 在javascript中的二维对象数组中查找值的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10505284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:06:30  来源:igfitidea点击:

Finding index of value in two dimensional array of objects in javascript

javascriptarraysmultidimensional-arrayfor-loop

提问by RyanP13

I have a 2D array of objects like so:

我有一个二维对象数组,如下所示:

[[{id: 123}, {id: 456}, {id: 789}], [{id: 111}, {id: 222}, {id: 333}], [{id: 444}, {id: 555}, {id: 666}], [{id: 777}]]

I need to find the index of the id at the top array level.

我需要在顶级数组级别找到 id 的索引。

So if i was to search for and id property with value '222' i would expect to return an index of 1.

因此,如果我要搜索值为 '222' 的 id 属性,我希望返回索引为 1。

I have tried the following:

我尝试了以下方法:

var arr = [[{id: 123}, {id: 456}, {id: 789}], [{id: 111}, {id: 222}, {id: 333}], [{id: 444}, {id: 555}, {id: 666}], [{id: 777}]],
    len = arr.length
    ID = 789;

for (var i = 0; i < len; i++){
    for (var j = 0; j < arr[i].length; j++){
        for (var key in o) {
            if (key === 'id') {
                if (o[key] == ID) {
                    // get index value 
                }
            }
        }           
    }
}

回答by maerics

Wrap your code in a function, replace your comment with return i, fallthrough by returning a sentinel value (e.g. -1):

将您的代码包装在一个函数中,return i通过返回标记值(例如 -1)将您的注释替换为, fallthrough :

function indexOfRowContainingId(id, matrix) {
  for (var i=0, len=matrix.length; i<len; i++) {
    for (var j=0, len2=matrix[i].length; j<len2; j++) {
      if (matrix[i][j].id === id) { return i; }
    }
  }
  return -1;
}
// ...
indexOfRowContainingId(222, arr); // => 1
indexOfRowContainingId('bogus', arr); // => -1

回答by cliffs of insanity

Since you know you want the id, you don't need the for-inloop.

既然你知道你想要id,你就不需要for-in循环。

Just break the outer loop, and iwill be your value.

只需打破外循环,i就会成为你的价值。

var arr = [[{id: 123}, {id: 456}, {id: 789}], [{id: 111}, {id: 222}, {id: 333}], [{id: 444}, {id: 555}, {id: 666}], [{id: 777}]],
    len = arr.length
    ID = 789;

OUTER: for (var i = 0; i < len; i++){
    for (var j = 0; j < arr[i].length; j++){
        if (arr[i][j].id === ID)
            break OUTER;           
    }
}

Or make it into a function, and return i.

或者把它变成一个函数,然后返回i