[英]Filtering array of objects against another array of objects?
customerProducts: [
{
name: "foo",
id: 123
},
{
name: "test",
id: 44
}
]
otherProducts: [
{
name: "other",
id: 44
},
{
name: "test",
id: 21
}
]
I want to iterate through customerProducts
, which is an array of objects.我想遍历customerProducts
,它是一个对象数组。 I want to filter the customerProducts
that have an ID that another array of objects, otherProducts
, has.我想过滤具有另一个对象数组otherProducts
具有的 ID 的customerProducts
。 So for examople, I'd want the returned result in this case to be:因此,例如,我希望在这种情况下返回的结果是:
{
name: "test",
id: 44
}
since otherProducts
has an id
of 44.因为otherProducts
的id
为 44。
I was thinking of mapping through otherProducts
and just returning an array of IDs, then running a forEach
on that but that seems like a long way of doing it.我正在考虑通过otherProducts
映射并只返回一组 ID,然后在其上运行forEach
但这似乎是很长的路要走。
Create an indexed Set
of the values to filter by ( id
from otherProducts
) then filter customerProducts
by that Set创建要过滤的值的索引Set
(来自otherProducts
id
),然后按该集过滤customerProducts
const customerProducts = [{name: "foo",id: 123},{name: "test",id: 44}] const otherProducts = [{name: "other",id: 44},{name: "test",id: 21}] const otherProductIds = new Set(otherProducts.map(({ id }) => id)) const filteredCustomerProducts = customerProducts.filter(({ id }) => otherProductIds.has(id)) console.info(filteredCustomerProducts)
declare customerProducts
, otherProducts
as JS array variable and use JS Array filter find functions将customerProducts
, otherProducts
声明为 JS 数组变量并使用 JS Array 过滤器查找函数
let customerProducts = [
{
name: "foo",
id: 123
},
{
name: "test",
id: 44
}
]
let otherProducts = [
{
name: "other",
id: 44
},
{
name: "test",
id: 21
}
];
let filtered = customerProducts.filter( el => otherProducts.find( e => e.id == el.id) )
console.log(filtered);
This can be done by using array methods filter and some .这可以通过使用数组方法filter和some来完成。
customerProducts.filter((x)=> otherProducts.some(y=> y.id === x.id));
Explanation: filter method will call each and every element in the otherProducts
array and check if the id
of customerProduct
is present in otherProducts
for at least one element.说明: filter 方法将调用otherProducts
数组中的每一个元素,并检查customerProduct
的id
是否存在于otherProducts
中至少一个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.