遍历嵌套数组以匹配ID

时间:2019-04-08 09:43:38

标签: javascript arrays

我有一组嵌套数组的数据,这些数组可能为空,或者实际上可能包含一个ID,如果其中一个数组的ID与与其比较的ID匹配,我想将所有数据放入其中匹配的数组,并将其分配给要使用的变量...

示例:

data = [[],[],[],[],[],[],[],[],[{"id":"123","name":"DARES HOUSE 2019","startDate":null,"endDate":null,"country":null,"city":null,"type":"Event","members":null}],[],[],[],[],[],[],[],[],[],[],[]]

id = 123

matchedArray =
  for (var i = 0; i < potentialEvents.length; i++) {
    for (var j = 0; j < potentialEvents[i].length; j++) {

      if (id === potentialEvents[i].id) {
        return;
      }
    }
  }
console.log(matchedArray)

我正试图拥有它,所以matchArray将是具有匹配ID的数组!

如果可以帮助,非常感谢!

3 个答案:

答案 0 :(得分:3)

您可以结合使用.map.filter.flat

var data = [[],[],[],[],[],[],[],[],[{"id":"123","name":"DARES HOUSE 2019","startDate":null,"endDate":null,"country":null,"city":null,"type":"Event","members":null}],[],[],[],[],[],[],[],[],[],[],[]]

var id = 123;

var matchedArray = data.map( arr => {
   return arr.filter(x => x.id == id);
}).flat();

console.log(matchedArray);

答案 1 :(得分:2)

您可以使用Array#filter方法来过滤内部数组,并使用Array#flatMap方法来将过滤后的数组连接为一个数组。

let data = [[],[],[],[],[],[],[],[],[{"id":"123","name":"DARES HOUSE 2019","startDate":null,"endDate":null,"country":null,"city":null,"type":"Event","members":null}],[],[],[],[],[],[],[],[],[],[],[]];
let id = 123;

let matchedArray = data.flatMap(arr => arr.filter(obj => obj.id == id))
console.log(matchedArray)

答案 2 :(得分:0)

我建议使用.some,而不要使用.filter / .map / .flatMap。主要优点是它允许在找到元素时停止遍历数组。

在具有大量数据的大型阵列上,效率更高(快约50倍):jsperf test

const data = [[],[],[],[],[],[],[],[],[{"id":"123","name":"DARES HOUSE 2019","startDate":null,"endDate":null,"country":null,"city":null,"type":"Event","members":null}],[],[],[],[],[],[],[],[],[],[],[]]

const id = 123;
let matchedArray = null;

data.some((a) => {
  return a.some((v) => {
    if (v != null && v.id == id) {
      matchedArray = a;
      return true;
    }
  });
});

console.log(matchedArray);