React:使用多个可能值的数组过滤json对象

问题描述

我有一个json对象
我像这样将它导入了react组件

import data from "../data/data.json";

这是我的json对象

{
"Cocktail": [
  {
        "id": 1,"name": "PL","illustration": "img1","ingredient": [{"percent": "1/10","ingredientname": "br"},{"percent": "4/10","ingredientname": "or"},{"percent": "5/10","ingredientname": "vo"}]
  },...
  {
    "id": 3,"name": "AN","illustration": "img3","ingredient": [{"percent": "2/10",{"percent": "2/10","ingredientname": "li"},{"percent": "6/10","ingredientname": "ri"}
      ] 
    }
  ] 
}

我有这个数组

ingred = ["br","or"]

我想过滤json对象文件: IngredientsName,其具有ingred数组的对应值之一,并返回关联的每个元素的名称

我尝试过

  return (
    <>
    {
    data.Cocktail
      .map((cocktail) => {
        return (
          <>
          {
           cocktail.ingredient.filter(ingredientcocktail => ingredientcocktail.ingredientname === ingred).map((ingredientcocktail) => {
                return (
                    <span key={cocktail.name}>
                    </span>
                );
              })
          }
          </> 
        );
      })
    }
  </>
  );

但是它不起作用:我不知道如何通过第二个数组的项进行过滤。 有人可以帮我吗?

解决方法

对不起,无法为您提供ReactJs,但这应该可以在“普通” JS中使用:

let obj = {
    "Cocktail": [
      {
            "id": 1,"name": "PL","illustration": "img1","ingredient": [{"percent": "1/10","ingredientname": "br"},{"percent": "4/10","ingredientname": "or"},{"percent": "5/10","ingredientname": "vo"}]
      },{
        "id": 3,"name": "AN","illustration": "img3","ingredient": [{"percent": "2/10",{"percent": "2/10","ingredientname": "li"},{"percent": "6/10","ingredientname": "ri"}
          ] 
        },{
          "id": 4,"name": "asdasd","illustration": "asdasd","ingredientname": "asdasd"},"ingredientname": "asdasd"}
            ] 
          }
      ] 
    };
let wanted = ["br","or"]
let res = obj.Cocktail.filter(
              el => el.ingredient.some( 
                   i => wanted.some(w => w == i.ingredientname)
              )
          ).map(cocktail => cocktail.name);
console.log(res)

(这并不是“最有效的方式”,因此,如果您有更有效的方式来做,请随时回答,不要在评论中抱怨它)

,

我想我找到了解决方法:

data.Cocktails
  .map((cocktail) => {
    return (
      <>
      {
       cocktail.ingredient
        .filter(ingredientcocktail => ingred .includes(ingredientcocktail.ingredientname))
        .map((ingredientcocktail) => {
            return (
                <div key={ingredientcocktail.ingredientname}>
                  {cocktail.name}
                </div>
            );
          })
      }
      </> 
    );
  })
}

谢谢您的回答。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...