【问题标题】:GraphQL data to ObjectGraphQL 数据到对象
【发布时间】:2020-01-09 09:29:12
【问题描述】:
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)

我觉得有点过分了。无论如何我可以在没有这两个步骤的情况下获得最终的对象吗?。

【问题讨论】:

    标签: javascript reactjs graphql


    【解决方案1】:

    在现代 JS (ES2019+) 中你可以使用Object.fromEntries:

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

    【讨论】:

    • 这仍然返回一个数组吗? [ ["0", ["bilia", { "originalName": "bilia.png" }]], ["1", ["superloon", { "originalName": "superloon.png" }]] ]我在这里期望的是一个对象{"bilia": "bilia.png"}
    • @IanTran 抱歉,已修复错字。
    猜你喜欢
    • 2018-11-21
    • 2019-08-02
    • 1970-01-01
    • 2019-03-10
    • 2018-09-06
    • 2017-02-07
    • 2018-10-18
    • 2019-06-18
    • 2018-08-15
    相关资源
    最近更新 更多