简体   繁体   中英

Using JavaScript, how can I filter an array of objects using multiple criteria in a child object

I want to get all the customers who have returned product "2":

 // Note that in production this array is much longer const customers = [ { "customerId": "1", "products": [ { "productId": "1", "status": "purchased" }, { "productId": "2", "status": "purchased" } ] }, { "customerId": "2", "products": [ { "productId": "1", "status": "purchased" }, { "productId": "2", "status": "returned" } ], } ] const returns = customers.filter((customer) => customer.products.some((product) => product.productId === "2" && product.status === "returned") ); console.log(returns);

I thought my use of filter would work - but I am guessing some() doesn't work with multiple criteria? Or am I doing something else wrong? Or is there a better way?

Your condition product.productId === "2" && product.status === "returned" does match only one object

if the productId is '2' AND the status is 'returned' matches the last object which is returned.

if you only want the products that have the Id of '2' then it should be product.productId === "2"

Hope this makes sense

Try using some function for the products.

 const customers = [{ "customerId": "1", "products": [{ "productId": "1", "status": "purchased" }, { "productId": "2", "status": "purchased" } ] }, { "customerId": "2", "products": [{ "productId": "1", "status": "purchased" }, { "productId": "2", "status": "returned" } ], } ] const returns = customers.filter((customer) => customer.products.some((product) => product.productId === "2" && product.status === "returned")) console.log(returns);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM