[英]How to reduce array of objects if another array contains objects?
I have two arrays of objects, one contains Shops
with it's id
, name
etc. and another with Products
each product has shop_id
property in it and i have a filter function which by passing Shop
id
returns all Products
of that shop.我有两个对象数组,一个包含
Shops
及其id
、 name
等,另一个包含Products
每个产品都有shop_id
属性,我有一个过滤器功能,通过传递Shop
id
返回该商店的所有Products
。 The issue is that there could be Shops
without items and i would remove that Shops
from the array.问题是可能有没有物品的
Shops
,我会从数组中删除这些Shops
。
So i was going to use .reduce
to do it with a .filter on Products
Array but i can't get on how i can return the array with only Shops that has some items所以我打算用
.reduce
对一个.filter做Products
阵列,但我不能就如何我可以返回,只有商店阵列获得,有一些项目
i was trying to do something like this我试图做这样的事情
var shops = [ { id: 123, desc: 'Pippo' }, { id: 124, desc: 'Pluto' }, { id: 125, desc: 'Gianni' } ] const products = [ { id: 1, desc: 'Car', shop: 123 }, { id: 2, desc: 'Jet', shop: 123 }, { id: 3, desc: 'Pizza', shop: 124 } ] shops = shops.reduce((a,b) => { products.filter((item) => item.menu === b.id).length ? b : a }) console.log(shops) // shouldn't return shop 125 as no items in products for its id.
I think you could accomplish this with array.filter and array.some :我认为你可以用array.filter和array.some来完成这个:
const shops = [{ id: 'shop1' },{ id: 'shop2' },{ id: 'shop3'},] const products = [ { pid: 'product1', shop: 'shop1'}, { pid: 'product3', shop: 'shop3'}, ]; const shopsWithProducts = shops.filter(shop => products.some(p => p.shop === shop.id)); console.log(shopsWithProducts);
You could group the products
based on their shop
property, creating a lookup object in the process.您可以根据
products
的shop
属性对products
分组,在此过程中创建查找对象。 This method should be faster when working with large amounts of shops and products, since you only iterate products
once.这种方法在处理大量商店和产品时应该更快,因为您只迭代
products
一次。
var shops = [ { id: 123, desc: 'Pippo' }, { id: 124, desc: 'Pluto' }, { id: 125, desc: 'Gianni' } ]; const products = [ { id: 1, desc: 'Car', shop: 123 }, { id: 2, desc: 'Jet', shop: 123 }, { id: 3, desc: 'Pizza', shop: 124 } ]; const productsByShop = groupBy(products, product => product.shop); shops = shops.filter(shop => productsByShop.get(shop.id)); console.log(shops) // shouldn't return shop 125 as no items in products for its id. // helper function groupBy(iterable, fn) { const groups = new Map(); for (const item of iterable) { const key = fn(item); if (!groups.has(key)) groups.set(key, []); groups.get(key).push(item); } return groups; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.