我有一个对象数组,我想根据任何键的值是否与另一个数组中的任何值匹配来过滤以创建新数组。
const array1 = [{name: 'pink', id: 13}, {name: 'orange', id: 17}, {name: 'red, id: 64}, {name: 'purple', id: 47}, {name: 'yellow', id: 23}, {name: 'gray', id: 2}, {name: 'black', id: 200}, {name: 'violet', id: 4}]
const array2 = ['red', 'blue', 'green', 'pink']
我尝试在返回函数中使用for ... of循环,但这给了我错误。
const array3 = array1.filter(color => {
for (mainColor of array2){
return color.name === mainColor
}
});
这有效,但显然不是最好的方法。
const array3 = array1.filter(color => {
return (color.main === 'red') || (color.main === 'blue')
});
如何从array1获取第三个数组,该数组仅包含array1.name与array2中的值匹配的对象?
是否可以使用ES6或Lodash?
提前致谢!
答案 0 :(得分:4)
几乎在那里,而不是for-loop使用includes
和 return
const array3 = array1.filter(color => {
return array2.includes ( color.name );
});
或
const array3 = array1.filter( color => array2.includes ( color.name ) );
答案 1 :(得分:3)
让我给出一个替代方案,它有更多的代码,但也更高效,因为它只需要扫描array2
一次:
const array1 = [{name: 'pink', id: 13}, {name: 'orange', id: 17}, {name: 'red', id: 64}, {name: 'purple', id: 47}, {name: 'yellow', id: 23}, {name: 'gray', id: 2}, {name: 'black', id: 200}, {name: 'violet', id: 4}],
array2 = ['red', 'blue', 'green', 'pink'];
const colorSet = new Set(array2),
array3 = array1.filter(color => colorSet.has(color.name));
console.log(array3);
答案 2 :(得分:1)
使用数组' includes()
:
const array1 = [{name: 'pink', id: 13}, {name: 'orange', id: 17}, {name: 'red', id: 64}, {name: 'purple', id: 47}, {name: 'yellow', id: 23}, {name: 'gray', id: 2}, {name: 'black', id: 200}, {name: 'violet', id: 4}]
const array2 = ['red', 'blue', 'green', 'pink'];
const array3 = array1.filter(color => array2.includes(color.name));
console.log(array3);

答案 3 :(得分:0)
filter
方法已经迭代了每个项目。如果元素存在于第二个数组中,则只需return
true
(使用indexOf
或includes
)
const array1 = [{name: 'pink', id: 13}, {name: 'orange', id: 17}, {name: 'red', id: 64}, {name: 'purple', id: 47}, {name: 'yellow', id: 23}, {name: 'gray', id: 2}, {name: 'black', id: 200}, {name: 'violet', id: 4}]
const array2 = ['red', 'blue', 'green', 'pink'];
let filteredArray = array1.filter(e => array2.indexOf(e.name) > -1);
console.log(filteredArray);

答案 4 :(得分:0)
我知道indexOf
可能看起来有点过时了,ES5-ish,但它仍然可以完成这项任务:
const array1 = [{name: 'pink', id: 13}, {name: 'orange', id: 17}, {name: 'red', id: 64}, {name: 'purple', id: 47}, {name: 'yellow', id: 23}, {name: 'gray', id: 2}, {name: 'black', id: 200}, {name: 'violet', id: 4}],
array2 = ['red', 'blue', 'green', 'pink'];
let array3 = array1.filter(x => array2.indexOf(x.name) != -1)
console.log(array3)