首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >根据数组嵌套值筛选数组

根据数组嵌套值筛选数组
EN

Stack Overflow用户
提问于 2018-05-28 13:15:47
回答 1查看 34关注 0票数 1

我有一系列的结果。我希望将结果过滤到一个数组中,该数组的category至少有一个cat_id1的对象。我该怎么做呢?

代码语言:javascript
复制
"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": [],
  },
]

我的尝试是:

代码语言:javascript
复制
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)
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-28 13:18:59

.filter中使用.some检查是否有任何category对象具有匹配的cat_id

代码语言:javascript
复制
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);

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50559514

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档