Home > Blockchain >  Unable to access nested array object property in JavaScript
Unable to access nested array object property in JavaScript

Time:04-03

I am trying to display the product array information such as name image url from the categories object. Here is the structure of the object.

{
  "categories": [
    {
      "__typename": "Category",
      "categoryId": "aeb50ed6-580d-a065-383a-e3932fbec6a1",
      "name": "Electronics",
      "products": [
        {
          "__typename": "Product",
          "productId": "f1ea5d7a-c26e-d850-52b5-9ac4c19668f2",
          "name": "Small Soft Salad",
          "price": 841,
          "discount": 23,
          "unitsSold": 5,
          "images": [
            {
              "__typename": "ProductImage",
              "url": "https://shoplly-api.techawks.io/storage/511dBXGmAtL._AC_UL320_.jpg"
            },
            {
              "__typename": "ProductImage",
              "url": "https://shoplly-api.techawks.io/storage/71MIvKxxSvL._AC_UL320_.jpg"
            },
            {
              "__typename": "ProductImage",
              "url": "https://shoplly-api.techawks.io/storage/81loLb-NTYL._AC_UL320_.jpg"
            },
            {
              "__typename": "ProductImage",
              "url": "https://shoplly-api.techawks.io/storage/81goU9h-jnL._AC_UL320_.jpg"
            },
            {
              "__typename": "ProductImage",
              "url": "https://shoplly-api.techawks.io/storage/61pUul1oDlL._AC_UL320_.jpg"
            }
          ]
        },
        {
          "__typename": "Product",
          "productId": "b2d38cf6-b8c7-6449-e13a-8ef3bdd12dd0",
          "name": "Tasty Plastic Pants",
          "price": 250,
          "discount": 44,
          "unitsSold": 2,
          "images": [
            {
              "__typename": "ProductImage",
              "url": "https://shoplly-api.techawks.io/storage/511dBXGmAtL._AC_UL320_.jpg"
            },
            {
              "__typename": "ProductImage",
              "url": "https://shoplly-api.techawks.io/storage/61pUul1oDlL._AC_UL320_.jpg"
            },
            {
              "__typename": "ProductImage",
              "url": "https://shoplly-api.techawks.io/storage/61S0sV1a57L._AC_UL320_.jpg"
            },
            {
              "__typename": "ProductImage",
              "url": "https://shoplly-api.techawks.io/storage/81WnMBnbWSL._AC_UL320_.jpg"
            },
            {
              "__typename": "ProductImage",
              "url": "https://shoplly-api.techawks.io/storage/71266hQjO8L._AC_UL320_.jpg"
            }
          ]
        },
        {
          "__typename": "Product",
          "productId": "4ac166a1-9636-d299-e7a6-13a9c451582c",
          "name": "Fantastic Plastic Pizza",
          "price": 192,
          "discount": 26,
          "unitsSold": 18,
          "images": [
            {
              "__typename": "ProductImage",
              "url": "https://shoplly-api.techawks.io/storage/81WFWi9sKlL._AC_UL320_.jpg"
            },
            {
              "__typename": "ProductImage",
              "url": "https://shoplly-api.techawks.io/storage/71ZE0VUjkSL._AC_UL320_.jpg"
            },
            {
              "__typename": "ProductImage",
              "url": "https://shoplly-api.techawks.io/storage/81WnMBnbWSL._AC_UL320_.jpg"
            },
            {
              "__typename": "ProductImage",
              "url": "https://shoplly-api.techawks.io/storage/61S0sV1a57L._AC_UL320_.jpg"
            },
            {
              "__typename": "ProductImage",
              "url": "https://shoplly-api.techawks.io/storage/81zbIt0p5qL._AC_UL320_.jpg"
            }
          ]
        },
        {
          "__typename": "Product",
          "productId": "c9f91096-4e77-30e8-fbde-c14f97d25d77",
          "name": "Tasty Rubber Car",
          "price": 611,
          "discount": 4,
          "unitsSold": 27,
          "images": [
            {
              "__typename": "ProductImage",
              "url": "https://shoplly-api.techawks.io/storage/81WFWi9sKlL._AC_UL320_.jpg"
            },
            {
              "__typename": "ProductImage",
              "url": "https://shoplly-api.techawks.io/storage/71WCgLmDx7L._AC_UL320_.jpg"
            },
            {
              "__typename": "ProductImage",
              "url": "https://shoplly-api.techawks.io/storage/71nJ48O6aFL._AC_UL320_.jpg"
            },
            {
              "__typename": "ProductImage",
              "url": "https://shoplly-api.techawks.io/storage/81goU9h-jnL._AC_UL320_.jpg"
            },
            {
              "__typename": "ProductImage",
              "url": "https://shoplly-api.techawks.io/storage/71MIvKxxSvL._AC_UL320_.jpg"
            }
          ]
        },

Here is what I tried to access the name and image url of the product array.

import React from "react";
import { useQuery, gql } from "@apollo/client";
import useStore from "./store/store";

const PRODUCT_QUERY = gql`
  {
    categories {
      categoryId
      name
      products {
        productId
        name
        price
        discount
        unitsSold
        images {
          url
        }
      }
      subCategories {
        name
        subCategoryId
        categoryId
      }
    }
  }
`;

const Hero = () => {
  const filter = useStore((state) => state.filter);
  const furniture = useStore((state) => state.furnitures);
  const electronic = useStore((state) => state.electronics);
  const accessorie = useStore((state) => state.accessories);
  const vehicle = useStore((state) => state.vehicles);
  const fashion = useStore((state) => state.fashions);
  const { data, loading, error } = useQuery(PRODUCT_QUERY);
  console.log(JSON.stringify(data, null, 2));
  return (
    <div>
      <div className="flex space-x-10 justify-center items-center">
        <div onClick={furniture}>Furnitires</div>
        <div onClick={electronic}>Electroinics</div>
        <div onClick={accessorie}>Vehicles</div>
        <div onClick={vehicle}>Accessories</div>
        <div onClick={fashion}>Fashion</div>
      </div>
      <div className="flex space-x-16 p-4 mt-10">
        <div className=" w-64  bg-green-500">
          {data?.categories[filter]?.subCategories?.map((launch) => (
            <div key={launch.name}>{launch.name}</div>
          ))}
        </div>
        <div className="flex-1 p-10 font text-2xl  bg-green-500 ">
          {" "}
          <div className="grid grid-cols-2 gap-2">
            {data?.categories[filter]?.products?.map((products) => (
              <div className="" key={products.name}>
                <div className="  bg-white rounded">
                  <div>{products?.name}</div>
                  <div>{products?.price}</div>
                  <div>
                    <img src={products?.images?.url} />
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

export default Hero;

So, I can display the product name but not the product image url.

What can I do to display product image url along with it's product name?

Thanks

CodePudding user response:

Images is an array containing multiple images. You'll need to a secondary map over the array to access the URL on each object.

{data?.categories[filter]?.products?.map((products) => (
              <div className="" key={products.name}>
                <div className="  bg-white rounded">
                  <div>{products?.name}</div>
                  <div>{products?.price}</div>
                  <div>
                    {products.images.map((img) =>
                       <img src={img.url} />
                      )}
                  </div>
                </div>
              </div>
            ))}

CodePudding user response:

Images itself is an array of objects, so its required to map over it again

<div>
  {products?.images.map((img) => <img src={img.url} />)}
</div>   

       

If you want to show only just one image and that too the first one then we can do it as per @ray comment

<div>
  <img src={products?.images[0]?.url} />
</div>
  • Related