【发布时间】:2019-12-25 20:44:29
【问题描述】:
我的 React 应用程序中有一个包含食谱的对象,我试图根据点击的成分过滤器对其进行过滤。每个菜谱都有一个 JSON 字符串,其中填充了菜谱(请参阅下面的菜谱对象)。
目前我在成功过滤我的食谱列表后卡住了,但最终得到一个空对象列表和正确过滤的食谱对象。
我需要以某种方式移除或减少(请参阅下面我徒劳的尝试)这些空对象。
const filteredArray = this.state.recipes.map(recipe => {
const ingredients = JSON.parse(recipe.ingredients);
const filtered = ingredients.filter(ingredient => selectedFilters.includes(ingredient.id))
.reduce(() => {
return recipe;
}, {});
});
下面是我的this.state.recipes 对象的示例:
{
id: 42
image: "/path/to/image.png"
ingredients: "[{"id": 192, "name": "Cachaça"},{"id": 243, "name": "Sugar"},{"id": 27, "name": "Lime"},{"id": 28, "name": "Icecubes"}]"
name: "Caipirinha"
short: "short description"
},
{
id: 43
image: "/path/to/image.png"
ingredients: "[{"id": 192, "name": "Cachaça"},{"id": 33, "name": "Espresso"},{"id": 243, "name": "Sugar"},{"id": 27, "name": "Lime"},{"id": 28, "name": "Icecubes"}]"
name: "Caipirinha coffee"
short: "short description"
}
【问题讨论】:
标签: json reactjs ecmascript-6 filter reduce