gpt4 book ai didi

javascript - 如何迭代数组中的值以匹配对象中的值并返回相应的对象?

转载 作者:行者123 更新时间:2023-12-02 23:06:38 24 4
gpt4 key购买 nike

我尝试在另一个包含大量对象的数组中搜索我在数组中获得的任何值。我尝试使用 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)的数组的错误,这将是锦上添花。

最佳答案

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);

关于javascript - 如何迭代数组中的值以匹配对象中的值并返回相应的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57560383/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com