根据嵌套数组值过滤数组
Posted
技术标签:
【中文标题】根据嵌套数组值过滤数组【英文标题】:filter array accoring to its nested array value 【发布时间】:2018-11-06 15:25:29 【问题描述】:我有一系列结果。我想将结果过滤到一个数组,其category
s 至少有一个对象的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)
【问题讨论】:
是的,它可以是空的,也可以有 3 个您可以在上面看到的对象 【参考方案1】:在.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);
【讨论】:
【参考方案2】:您应该在产品级别上进行过滤 results: []
和谓词匹配预期类别的 id 嵌套 find some 像这样; .filter(product => product.category.some(cat => cat.cat_id === 1)
确保类别始终是一个数组,否则您必须检查更多。
【讨论】:
以上是关于根据嵌套数组值过滤数组的主要内容,如果未能解决你的问题,请参考以下文章