在数组数组中搜索对象

时间:2017-06-01 06:30:55

标签: javascript arrays

我有一个数组,里面装有数组,每个数组包含多个对象。我想知道我的对象是否存在于那里

我做了一个jsfiddle以保持简单 - https://jsfiddle.net/rgnoz31y/1/

或者,如果您只想查看我的代码,请在下面填写:

blackChains = [];

blackChains.push([{x: 1, y: 2}, {x: 1, y: 3}]);
blackChains.push([{x: 3, y: 4}, {x:4, y: 4}, {x:5, y: 4}]);

currentPiece = {x: 1, y: 3};

const isInChain = blackChains.map(g => g[{}]).includes(currentPiece);

console.log(isInChain);

当它应该为真时,它当前返回false

5 个答案:

答案 0 :(得分:0)

当您使用箭头功能时,我假设您使用的是ES6。

使用Spreads,我可以创建一个包含所有数组项https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator

的数组
acc.push(...item);

includes通常可以使用,但它仅适用于按引用进行调用,而不是按值调用,例如这可能会失败:

console.log([{x: 1, y: 2}, {x: 1, y: 3}].includes(currentPiece));
如果至少有一个项与条件匹配,则

Some返回true。通过将Item和Search Element更改为JSON String,我们可以按Value检查。



blackChains = [];

blackChains.push([{x: 1, y: 2}, {x: 1, y: 3}]);
blackChains.push([{x: 3, y: 4}, {x:4, y: 4}, {x:5, y: 4}]);

currentPiece = {x: 1, y: 3};

const isInChain = blackChains.reduce((acc, item) => {
  acc.push(...item);
  return acc;
}, []).some(item => JSON.stringify(item) === JSON.stringify(currentPiece));

console.log(isInChain);




答案 1 :(得分:0)

如前评论,

  

g [{}]将返回undefined。它被解释为g [“Object object”]

blackChains.map(g => g[{}])将返回一个长度为n的数组,其全部为未定义。

您可以使用递归来遍历r嵌套数组,并在获取对象时将其停止。

var blackChains = [];

blackChains.push([{x: 1, y: 2}, {x: 1, y: 3}]);
blackChains.push([{x: 3, y: 4}, {x:4, y: 4}, {x:5, y: 4}]);


var currentPiece = { x: 1, y: 3 };

function searchObjInArray(arr, search) {
  if (Array.isArray(arr)) {
    return arr.some(function(item) {
      return searchObjInArray(item, search)
    })
  } else if (typeof arr === "object") {
    var valid = true;
    for (var k in search) {
      valid = valid && search[k] === arr[k];
      if (!valid) break;
    }
    return valid;
  }
}

var isInChain = searchObjInArray(blackChains, currentPiece)
console.log("isInChain: ", isInChain);

currentPiece.y = 4;

isInChain = searchObjInArray(blackChains, currentPiece)
console.log("isInChain: ", isInChain);

答案 2 :(得分:0)

替换为:



const isInChain = blackChains.findIndex(
  i => i.findIndex(a => a.x === currentPiece.x && a.y === currentPiece.y) > -1) > -1;




答案 3 :(得分:0)

您需要明确检查键值相等,如下所示:

blackChains = [];

blackChains.push([{x: 1, y: 2}, {x: 1, y: 3}]);
blackChains.push([{x: 3, y: 4}, {x:4, y: 4}, {x:5, y: 4}]);

currentPiece = {x: 1, y: 3};

const isInChain = blackChains.map(bc => !!bc.find(o => // return true a false for each index
  Object.keys(o).every(key => o[key] === currentPiece[key])));

console.log(isInChain);

答案 4 :(得分:0)

只需尝试使用Array#filter()并使用Array#find()找到与c数组匹配的匹配



function check(c){
blackChains = [];
blackChains.push([{x: 1, y: 2}, {x: 1, y: 3}]);
blackChains.push([{x: 3, y: 4}, {x:4, y: 4}, {x:5, y: 4}]);
return blackChains.filter(a=> a.find(a=> a.x == c.x && a.y == c.y ))[0] ? true : false;
}
console.log(check({x: 1, y:3}))
console.log(check({x: 1, y:31}))