简体   繁体   中英

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. 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. 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM