javascript - 将嵌套数组中的值添加到 div 类名中
问题描述
我还是 React、JavaScript 的新手,现在我遇到了一个问题。
是否可以将嵌套数组中的值添加到“父”div类中?
我有帖子,每个帖子都有类别数组。我需要遍历帖子并显示标题、文本。
我使用.map循环浏览帖子并显示标题和文本。但是如何遍历类别,获取名称值并将其添加到 div 类中?
数据:
const posts = [{
id: 1,
title: 'My awesome post title',
text: 'Hello this is the text',
categories: [{
id: 1,
name: 'category1'
}, {
id: 2,
name: 'category2'
}],
}, {
id: 2,
title: 'My post title 2',
text: 'Another post is here',
categories: [{
id: 1,
name: 'category3',
}, {
id: 2,
name: 'category10'
}]
}];
我需要这个:
<div className="posts">
<div className="post category1 category2">
<h2>My awesome post title<h2>
<p>Hello this is the text</p>
</div>
<div className="post category3 category10">
<h2>My post title 2<h2>
<p>Another post is here</p>
</div>
</div>
可能吗?
非常感谢
解决方案
有几种方法可以解决这个问题。一种方法是使用map
将类别名称提取到一个数组中,然后join
是带有空格的数组,如下所示:
let categories = [{
id: 1,
name: 'category1'
}, {
id: 2,
name: 'category2'
}];
const classList = categories.map( cat => cat.name ).join(" ");
console.log( classList );
另一种更复杂但可能 更有效的方法是使用reduce
:
let categories = [{
id: 1,
name: 'category1'
}, {
id: 2,
name: 'category2'
}];
const classList = categories.reduce( ( acc, cat ) => { acc += ` ${cat.name}`; return acc; }, "" );
console.log( classList );
由于您尚未在现有代码中发布,我不知道您将如何将这些解决方案准确地集成到您现有的方法中,但它们应该不会太难适应。
推荐阅读
- mongodb - mongodb:在其他文档中按条件查找所有记录
- html - 为什么标题框元素超出正文框元素?
- pyaudio - 如何在谷歌云外壳中安装 pyaudio 模块?
- php - 如何正确拆分包含 HTML 实体的 php 中的字符串
- javascript - PHP fputcsv函数不适用于对象数组
- javascript - 为什么在检查时跳过了函数并且未定义 onclick,尽管在脚本中定义了?
- css - 如何在 MUI Grid 中有不同的水平和垂直间距?
- python - 分页不适用于我的 Django 休息框架项目,我正在使用通用视图
- javascript - 尽管 URL 正确,Angular 路由器仍无法加载我的组件
- c# - .Net Core 控制台应用程序发布未在发布文件夹中创建任何文件