簡體   English   中英

GraphQL 數據到對象

[英]GraphQL data to Object

const data = useStaticQuery(graphql`
    query Draft {
      allFile(filter: { sourceInstanceName: { eq: "featuredProducts" } }) {
        edges {
          node {
            childImageSharp {
              fixed(width: 500, quality: 100) {
                ...GatsbyImageSharpFixed
                originalName
              }
            }
            name
          }
        }
      }
    }
  `)

我使用 GraphQL 查詢數據以獲取一些圖像。 我嘗試將輸出作為對象獲取,以便我可以使用圖像名稱作為鍵將其傳遞給 Image src。 我通過將它映射到一個數組,然后使用以下方法將其轉換為一個數組,成功地完成了它:

const images = data.allFile.edges.map(image => ({
    [image.node.name]: image.node.childImageSharp.fixed,
  }))

  const arrayToObject = array => {
    return Object.assign({}, ...array)
  }

  const FeaturedProducts = arrayToObject(images)

我覺得有點過分了。 無論如何,我可以在沒有這兩個步驟的情況下獲得最終對象嗎?

在現代 JS (ES2019+) 中,您可以使用Object.fromEntries

const featuredProducts = Object.fromEntries(data.allFile.edges.map(edge => {
  const image = edge.node;
  return [image.name, image.childImageSharp.fixed],
}));

暫無
暫無

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

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