简体   繁体   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
          }
        }
      }
    }
  `)

I query the data with GraphQL to get some images.我使用 GraphQL 查询数据以获取一些图像。 I try to get the output as an object so I can pass it to the Image src, using the image name as a key.我尝试将输出作为对象获取,以便我可以使用图像名称作为键将其传递给 Image src。 I've successfully done it by map it to an array, and then convert it to an array using these methods:我通过将它映射到一个数组,然后使用以下方法将其转换为一个数组,成功地完成了它:

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)

I feel it's a bit too much.我觉得有点过分了。 Is there anyway that I can get the final object without these 2 steps?.无论如何,我可以在没有这两个步骤的情况下获得最终对象吗?

In modern JS (ES2019+) you can use Object.fromEntries :在现代 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