简体   繁体   中英

Filter items from two different APIs

I have one API returning two arrays - one returning category name, category id. And another returning food name and category id. I need to map and render food according to the categories. Eg: Coke comes under Category beverage (category id 2).

How can I map and find which category and render it according?

Sample Category API :

{
"id": 1,
"en_description": "Beverage",
"en_org_description": null
},
{
"id": 2,
"en_description": "Wine",
"en_org_description": null
},
{
"id": 3,
"en_description": "By the Glass",
"en_org_description": null
}

Sample Food API:

{
"id": 1,
"category_id": 11,
"en_name": "The Bethany",
"en_description": "",
"price": 12,
"picture_url": null
},
{
"id": 2,
"category_id": 14,
"en_name": "Special French",
"en_description": "",
"price": 17,
"picture_url": null
},
{
"id": 3,
"category_id": 7,
"en_name": "Three Creeks IPA",
"en_description": "",
"price": 6,
"picture_url": null
},
{
"id": 4,
"category_id": 6,
"en_name": "Kids Cheeseburger",
"en_description": "",
"price": 9,
"picture_url": null
}

I need to map them accordingly instead of manually typed

Code:

function BottomContainer() {
  const [categories, setCategories] = useState([]);
  useEffect(() => {
    async function fetchData() {
      const response = await axios.get(
        "https://api-dev.souszen.com/location_and_menus?location_id=119&user_id=151"
      );
      // console.log(response.data.menus);
      setCategories(response.data.categories);
      // console.log(response.data.categories);
    }
    fetchData();
  }, []);

  // console.log(categories[0].en_description);

  return (
    <div className="mt-16">
      <MenuItems />

      {categories.map((category) => (
        <div key={category.id}>
          <p className="text-3xl font-semibold ml-4 mt-5">
            {category.en_description}
          </p>
          <FoodList name="California Roll" price="4.99" />
          <FoodList name="California Roll" price="4.99" />
          <FoodList name="California Roll" price="4.99" />
        </div>
      ))}
    </div>
  );
}
{categories.map((category) => (
    <div key={category.id}>
      <p className="text-3xl font-semibold ml-4 mt-5">
        {category.en_description}
      </p>
      {foods.map((food)=>{
          if(food.category_id===category.id)
          {
              <FoodList name={food.en_name} price={food.price} />
           }
      }}
    </div>
  ))}

For each category, you can iterate in foods array and check if they share the same category id then return that div

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM