簡體   English   中英

迭代嵌套在對象數組中的數組?

[英]Iterate over array nested in inside an array of objects?

我得到了以下 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"
            }
          }
        ]
      }
    }
  ]
}

我很難使用.map.forEach ,因為.map只是一直在重新創建數組。

如何在 JSX 中渲染 id、title、pricev2 部分?

例如 {product.title}、{product.priceV2}

我試過了

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

Then what?

您可以使用flatMap從變體節點展平mapped的數組。

 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)

可以說,每個node都可以被視為具有變體的產品(即使您的數據現在只包含一個元素),因此嵌套的 map 似乎是合適的。

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>
    ))}
  </>
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM