GraphQL 数据到对象


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

最新更新