filter数组符合其嵌套数组值

时间:2018-05-28 05:15:47

标签: javascript arrays json typescript ecmascript-6

我有一系列结果。我想将结果过滤到category s至少有一个对象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)
}

2 个答案:

答案 0 :(得分:3)

使用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);个对象中是否有匹配的{{1}}:

&#13;
&#13;
{{1}}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你应该对产品级results: []进行过滤,并使用嵌套的find some 来匹配预期类别的id; .filter(product => product.category.some(cat => cat.cat_id === 1)

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