繁体   English   中英

filter数组符合其嵌套数组值

[英]filter array accoring to its nested array value

我有一系列的结果。 我想将结果过滤到一个数组,该数组的category至少有一个cat_id1对象。 我怎样才能做到这一点?

"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)
}

.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); 

你应该在产品层面做过滤results: []和谓语匹配与预期类别的ID与嵌套找到一些像这样的; .filter(product => product.category.some(cat => cat.cat_id === 1)

确保该类别始终是一个数组,否则您必须检查更多

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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