我有一组对象。 样本对象就是这样
{
dish_name: { id: 1297, name: "Bellingham Estate Sauvignon Blanc" },
dish_has_categories: [
{
dishCatId: 11
},
{
dishCatId: 12
}
],
id:1
},
我想过滤dish_has_categories
数组应有dishCatId
= 11的对象,并且还要将此数组映射为最小格式。
这是我的数据集。
const data = [
{
dish_name: { id: 1297, name: "Bellingham Estate Sauvignon Blanc" },
dish_has_categories: [
{
dishCatId: 11
},
{
dishCatId: 12
}
],
id:1
},
{
dish_name: { id: 3432, name: "Burger" },
dish_has_categories: [
{
dishCatId: 7
},
{
dishCatId: 9
}
],
id:2
},
{
dish_name: { id: 4593, name: "Hoppers" },
dish_has_categories: [
{
dishCatId: 11
},
{
dishCatId: 12
}
],
id:3
},
{
dish_name: { id: 8709, name: "Bulsai" },
dish_has_categories: [
{
dishCatId: 2
},
{
dishCatId: 6
}
],
id:4
}
];
这是我的预期结果。
[
{
name: "Bellingham Estate Sauvignon Blanc",
id: 1
},
{
name: "Hoppers",
id: 3
}
];
对于我所做的过滤工作
data.filter(e=> e.dish_has_categories.find(el=> el.dishCatId = 11))
但似乎不起作用。如何使用JavaScript实现此目标?
答案 0 :(得分:2)
将分配=
更改为严格相等运算符===
,例如:
const data = [ { dish_name: { id: 1297, name: "Bellingham Estate Sauvignon Blanc" }, dish_has_categories: [ { dishCatId: 11 }, { dishCatId: 12 } ], id:1 }, { dish_name: { id: 3432, name: "Burger" }, dish_has_categories: [ { dishCatId: 7 }, { dishCatId: 9 } ], id:2 }, { dish_name: { id: 4593, name: "Hoppers" }, dish_has_categories: [ { dishCatId: 11 }, { dishCatId: 12 } ], id:3 }, { dish_name: { id: 8709, name: "Bulsai" }, dish_has_categories: [ { dishCatId: 2 }, { dishCatId: 6 } ], id:4 } ];
const result = data
.filter(e=> e.dish_has_categories.find(el => el.dishCatId === 11))
.map(res=>({id: res.id, name: res.dish_name.name}));
console.log(result)