Iterate over array nested in inside an array of objects?

Viewed 59

I got the following json:

{
  "nodes": [
    {
      "variants": {
        "nodes": [
          {
            "id": "98765",
            "title": "Gold",
            "priceV2": {
              "amount": "95.0",
              "currencyCode": "EUR"
            }
          },
          {
            "id": "65543",
            "title": "Silver",
            "priceV2": {
              "amount": "95.0",
              "currencyCode": "EUR"
            }
          },
          {
            "id": "12345",
            "title": "Gold",
            "priceV2": {
              "amount": "95.0",
              "currencyCode": "SEK"
            }
          },
          {
            "id": "11122",
            "title": "Black",
            "priceV2": {
              "amount": "95.0",
              "currencyCode": "EUR"
            }
          }
        ]
      }
    }
  ]
}

I have a hard time using .map or .forEach because .map just re-creates the array all the time.

How can I render the id, title, pricev2 part inside JSX?

Eg {product.title}, {product.priceV2}

I tried

products.map((product) => {
  return product.nodes
})

Then what?
2 Answers

You can use flatMap to flat the mapped array from variants nodes.

const products  = {
  "nodes": [
    {
      "variants": {
        "nodes": [
          {
            "id": "98765",
            "title": "Gold",
            "priceV2": {
              "amount": "95.0",
              "currencyCode": "EUR"
            }
          },
          {
            "id": "65543",
            "title": "Silver",
            "priceV2": {
              "amount": "95.0",
              "currencyCode": "EUR"
            }
          },
          {
            "id": "12345",
            "title": "Gold",
            "priceV2": {
              "amount": "95.0",
              "currencyCode": "SEK"
            }
          },
          {
            "id": "11122",
            "title": "Black",
            "priceV2": {
              "amount": "95.0",
              "currencyCode": "EUR"
            }
          }
        ]
      }
    }
  ]
}

const result = products.nodes.flatMap((product) => product.variants.nodes)

console.log(result)

Arguably each node could be considered a product with variants (even though your data only contains one element right now) so a nested map seems appropriate.

const data = {
  "nodes": [
    {
      "variants": {
        "nodes": [
          {
            "id": "98765",
            "title": "Gold",
            "priceV2": {
              "amount": "95.0",
              "currencyCode": "EUR"
            }
          },
          ...
        ]
      }
    }
  ]
}
return (
  <>
    {data.nodes.map((product, i) => (
      <div key={i}>
        {product.variants.nodes.map(variant => (
          <div key={variant.id}>
            <p>{variant.title}, {variant.priceV2.amount}</p>
          </div>
        ))}
      </div>
    ))}
  </>
)

Related