I have an array of results. I want to filter the results to an array whose category
s have at least one object with a cat_id
of 1
. How can I do that?
"results": [
{
"product_id": 1,
"title": "booking",
"draft": false,
"publish": true,
"category": [
{
"cat_id": 1,
"cat_name": "web",
"product": "booking"
}
],
},
{
"product_id": 2,
"title": "reading",
"draft": false,
"publish": true,
"category": [
{
"cat_id": 6,
"cat_name": "android",
"product": "asdasd"
}
],
},
{
"product_id": 3,
"title": "reading",
"draft": false,
"publish": true,
"category": [],
},
]
My attempt:
for (let i = 0; i < data.results.length; i++) {
this.webCatProducts = data.results[i].category.filter(d => d.cat_id == 1)
console.log(this.webCatProducts)
}
Use .some
inside the .filter
to check to see if any of the category
objects have a matching cat_id
:
const results=[{"product_id":1,"title":"booking","draft":!1,"publish":!0,"category":[{"cat_id":1,"cat_name":"web","product":"booking"}],},{"product_id":2,"title":"reading","draft":!1,"publish":!0,"category":[{"cat_id":6,"cat_name":"android","product":"asdasd"}],},{"product_id":3,"title":"reading","draft":!1,"publish":!0,"category":[],},]; const filtered = results.filter( ({ category }) => category.some(({ cat_id }) => cat_id === 1) ); console.log(filtered);
You should do filter on product level results: []
and predicate matched with expected category's id with nested find some like this; .filter(product => product.category.some(cat => cat.cat_id === 1)
Make sure that category is always an array otherwise you have to check more .
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.