【问题标题】:How to iterate through values in array to match value in objects and return corresponding object? [duplicate]如何遍历数组中的值以匹配对象中的值并返回相应的对象? [复制]
【发布时间】:2019-08-19 16:08:02
【问题描述】:

我尝试在另一个包含大量对象的数组中搜索我在数组中获得的任何值。 我尝试使用 lodash,但 vanilla 也可以。

我的参考数组是这样的:

let array1 = ["value1", "value2", "value8", "value9"]

我想在这个对象数组中找到这些值:

let array2 = [{
  key1: xxx
  key2: value1
  key3: xxxx
}, {
  key1: value2
  key2: xxxx
  key3: xxxx
}, {
  key1: xxx
  key2: xxx
  key3: value3
}]

我试过了

let finalData: []

let filterData = _.filter(array2, array1);
this.finalData = filterData

我希望返回一个包含所有匹配对象的数组:

[{
  key1: xxx
  key2: value1
  key3: xxxx
}, {
  key1: xxx
  key2: value2
  key3: xxxx
}]

我总是得到一个空数组。 我需要为每种方法组合一个吗?

奖励:如果它可以返回一个包含未找到值(value8、value9)的数组的错误,这将是锦上添花。

【问题讨论】:

  • array2.filter(it => array1.includes(it.key2))
  • 您尝试查找的值可能并不总是在key2 上,即我们应该查看对象的所有键,还是只查看特定的键?
  • @Shidersz,对不起,这不是精确的,确实可以将值放在任何地方。我已经更新了我的示例。

标签: javascript arrays object lodash


【解决方案1】:

let array1 = ["value1", "value2", "value8", "value9"];
let array2 = [
  {
    "key1": "xxx",
    "key2": "value1",
    "key3": "xxxx"
  }, {
    "key1": "xxx",
    "key2": "value2",
    "key3": "xxxx"
  },
  {
    "key1": "xxx",
    "key2": "value3",
    "key3": "xxxx"
  }
];

// copy the original array1
let noMatch = [...array1];

// iterate (and filter) through every element
// that array2 contains
let match = array2.filter(elem => {
  // iterate through every key in the element
  for (const key in elem) {
    // check if array1 has the value
    const found = array1.find(e => e === elem[key]);
    if (found) {
      // remove from noMatch the matched value
      noMatch = noMatch.filter(e => e !== found);
      // found
      return true;
    }
  }
  // Not found
  return false;
});

// matched elements
console.log('match', match);
// values that didn't match any element
console.log('noMatch', noMatch);

【讨论】:

  • 这项工作非常好,谢谢!知道如何获得未找到的值数组 ["value8", "value9"] 吗?我尝试添加 else if 但我不知道在这种情况下如何获取 array1 值...
  • @NuoNuoLeRobot 检查编辑。
  • 这是完美的,有 cmets 和一切!非常感谢您的宝贵时间,这是救命之恩!
猜你喜欢
  • 2011-10-12
  • 2021-12-16
  • 1970-01-01
  • 2020-07-21
  • 2020-07-03
  • 2015-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多