根据第二个数组中的值过滤对象数组 [英] Filter array of objects based on values in second array

查看:101
本文介绍了根据第二个数组中的值过滤对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,要根据任何键的值是否与另一个数组中的任何值匹配来过滤以创建新的数组.

I have an array of objects that I'd like to filter to create a new array based on whether or not the value of any key matches any value in another array.

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循环,但这给了我错误.

I've tried using a for...of loop inside of a return function but that is giving me errors.

    const array3 = array1.filter(color => {
        for (mainColor of array2){
            return color.name === mainColor 
        }
    });

这有效,但显然不是最佳方法.

This works but is clearly not the best way.

    const array3 = array1.filter(color => {
            return (color.main === 'red') || (color.main === 'blue')
        });

如何从array1获得第三个数组,该数组仅包含array1.name与array2中的值匹配的对象?

How can I get a third array from array1 that contains only the objects where the array1.name matches a value in array2?

ES6或Lodash是否有可能?

Is it possible with ES6 or Lodash?

提前谢谢!

推荐答案

几乎在那里,而不是for循环,请使用 includes return

Almost there, instead of for-loop use includes and return

const array3 = array1.filter(color => {
    return array2.includes ( color.name );
});

const array3 = array1.filter( color => array2.includes ( color.name ) );

这篇关于根据第二个数组中的值过滤对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆