首页 > 解决方案 > 将嵌套数组中的值添加到 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>

可能吗?

非常感谢

标签: javascriptreactjsecmascript-6

解决方案


有几种方法可以解决这个问题。一种方法是使用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 );

由于您尚未在现有代码中发布,我不知道您将如何将这些解决方案准确地集成到您现有的方法中,但它们应该不会太难适应。


推荐阅读