GraphQL data to Object

93 views Asked by At
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?.

1

There are 1 answers

2
Bergi On BEST ANSWER

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],
}));