在javascript中搜索一个对象数组

时间:2015-02-02 12:27:41

标签: javascript arrays

我有以下数组,其中我正在尝试搜索特定元素:

grid ({"row": row, "col": col})

有人可以提供有关如何在此数组中找到元素的建议吗?我尝试过类似的东西,但我似乎无法弄清楚我是否正确地做到了。

grid.indexOf([row, col])

任何建议都会很棒。

4 个答案:

答案 0 :(得分:1)

这不是数组,而是一个对象。

对于您可以使用的数组:

array.forEach(function(element, index, array) {});

因为这是一个对象,所以你需要做更多的工作:

Object.keys(grid).forEach(function(element, index, array) {
  if(element === some_random_name) {
    // Do whatever you need to here.
  }
});

答案 1 :(得分:0)

在数组内部保留对象,因此仅按值比较它们在JS中不起作用。

你可以用旧的方式(迭代)来做:

function indexOfCell(row, col){
  for(var i=0; i< grid.length;i++){
     if(grid[i].row === row && grid[i].col === col){ // this code can get complex, when working with many properties
       return i;
     }
  }
  return -1;
}

第二个解决方案是从Array原型过滤:

function filterByRowAndCol(element) {
  if (element.row === row && element.col === col) {
    return element;
  } else {
    invalidEntries++;
  }
}

var arrByRowAndCol = grid.filter(filterByID);

来源: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

答案 2 :(得分:0)

这是一个对象,用于访问您可以像这样使用的对象中的元素

grid = {"row": 10, "col": 12 };
alert( grid.row ); //will alert 10
alert( grid.col ); //will alert 12

答案 3 :(得分:0)

您正在使用对象,而不是数组。

您还需要优化对象的语法,以便正确使用它。试试这个:var grid = {'row': 'row', 'col': 'col'};

然后,您可以遍历对象属性以找到所需内容:

var findValue = function (someKey) {
    for (var property in grid) {
        if (grid.hasOwnProperty(property)) {
            if (property === someKey) {
                return grid.property // return the value
            }
        }
    }
};