首页 > 解决方案 > Javascript: filter an array of objects using an array

问题描述

I have an array of Objects:

[
    {id: 1, thing_id: 2},
    {id: 1, thing_id: 3},
    {id: 1, thing_id: 4}
]

and I want to filter that using an array of thing_ids:

[2,3]

I did look at filtering an array of objects using an array without nested loops js but it doesn't seem to work.

Clearly I need to use .filter somehow?

Mick

标签: javascriptarrays

解决方案


您可以通过以下方式使用Array.prototype.filter()和喜欢:Array.prototype.includes()

var arr1 = [{ id:1, thing_id: 2},
{ id: 1, thing_id: 3},
{ id: 1, thing_id: 4}];

var arr2 = [2,3]

var res = arr1.filter(i => arr2.includes(i.thing_id))
console.log(res);


推荐阅读