javascript - 在另一个数组中的数组中获取对象的属性值
问题描述
我正在使用 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"
}
解决方案
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;
推荐阅读
- c# - 使用 Autofac 在构造函数中注入带有 IOptions 的类
- c - C - sscanf 忽略 csv 文件中的逗号并读取相同的数据两次
- c# - NBitcoin 交易标志(秘密,布尔)给出错误。而不是 bool 它说通过 Coin
- r - 数据框的 R 嵌套/未嵌套会导致不同的对象
- javascript - Javascript突出显示切换开关上的差异
- r - 如何匹配仅包含任意顺序和任意数字的字符集的字符串?
- html - 背景图像未在css中显示
- java - Android Scroll View 与它下面的其他 View 重叠
- javascript - 安装 dojo/cli 时缺少写入权限(尽量避免使用 sudo)
- python - 删除字典中的空值