首页 > 解决方案 > 在另一个数组中的数组中获取对象的属性值

问题描述

我正在使用 Strapi 和 React 开发一个博客,并且博客中的文章有多个类别,我从 Strapi 得到一个像这样的 GraphQL 查询

(blogpostObject){
  
  "categories": [
    {
      "name": "Category 1"
    },
    {
      "name": "Category 2"
    },
  ],
  
}

我想访问每个类别的“名称”值,并用逗号分隔它们,每个类别都带有一个<a>带有指向另一个页面的链接的标签。

到目前为止,我只提出了这个解决方案

queryData.map(article => (
article.categories.map(category => category.name).toString().replace(/,/g, `, `) 

这将呈现:“Category 1,Category 2”,但我不知道如何<a>从这里将标签添加到它们中的每一个。

编辑:我使用 Gatsby 来构建这个项目,所以我使用 React Link 组件来处理内部链接。

这是一个示例 GraphQL 响应

{
  "data": {
    "allStrapiArticle": {
      "nodes": [
        {
          "title": "This is my second article",
          "slug": "this-is-my-second-article",
          "content": " Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
          "id": "Article_2",
          "author": {
            "name": "Average Joe"
          },
          "categories": [
            {
              "name": "Category 1"
            }
          ],
          "created_at": "Wednesday, June 24th 2020"
        }

标签: javascriptreactjsgraphqlstrapi

解决方案


import React from "react";

// this data would come from graphql instead
const data = {
  allStrapiArticle: {
    nodes: [
      {
        title: "This is my second article",
        slug: "this-is-my-second-article",
        content: " Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
        id: "Article_2",
        author: {
          name: "Average Joe"
        },
        categories: [
          {
            name: "Category 1"
          },
          {
            name: "Category 2"
          },
          {
            name: "Category 3"
          }
        ],
        created_at: "Wednesday, June 24th 2020"
      }
    ]
  }
};

const App = () => {
  return (
    <div>
      {data.allStrapiArticle.nodes.map(node => {
        return node.categories.map((category, index) => {
          return (
            <>
              <a href="/">{category.name}</a>
              {index < node.categories.length - 1 && ", "}
            </>
          );
        });
      })}
    </div>
  );
};

export default App;

编辑 adoring-forest-3yfnj


推荐阅读