【问题标题】:Filter list based on JSON string child基于 JSON 字符串子项的过滤列表
【发布时间】: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


    【解决方案1】:

    试试这个:

    this.state.recipes.filter(recipe => {
      const ingredients = JSON.parse(recipe.ingredients);
    
      return ingredients.findIndex(ingredient => selectedFilters.includes(ingredient.id)) !== -1;
    });
    

    【讨论】:

      猜你喜欢
      • 2014-08-19
      • 2014-07-15
      • 2011-12-05
      • 2021-11-18
      • 2020-07-30
      • 1970-01-01
      • 2020-01-29
      • 2018-08-14
      • 1970-01-01
      相关资源
      最近更新 更多