gpt4 book ai didi

javascript - 根据其嵌套数组值过滤数组

转载 作者:行者123 更新时间:2023-11-30 11:18:51 24 4
gpt4 key购买 nike

我有一系列结果。我想将结果过滤到一个数组中,该数组的 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);

关于javascript - 根据其嵌套数组值过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50559514/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com