本文介绍了在javascript中查找对象的二维数组中的值的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我需要在顶层数组中找到id的索引。因此,如果我要搜索和价值'222'的id属性,我期望返回1的索引。



我曾尝试以下方法:

  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; (var i = 0; i for(var j = 0; j
)如果(key ==='id'){
if(o [key] == ID){
//获取索引值





$ b $ div class =
$将你的代码包装在一个函数中,用 return i 替换你的注释,通过返回一个标记值(例如-1) :

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


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.

So if i was to search for and id property with value '222' i would expect to return an index of 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 
                }
            }
        }           
    }
}
解决方案

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

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

这篇关于在javascript中查找对象的二维数组中的值的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 12:10