我有一系列的结果。我希望将结果过滤到一个数组中,该数组的category
至少有一个cat_id
为1
的对象。我该怎么做呢?
"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": [],
},
]
我的尝试是:
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)
}
发布于 2018-05-28 13:18:59
在.filter
中使用.some
检查是否有任何category
对象具有匹配的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);
https://stackoverflow.com/questions/50559514
复制相似问题