javascript - 响应嵌套 json

标签 javascript json reactjs

假设我有一个 JSON 对象,例如:

posts = [
    {
        id: '1',
        title: 'Title of Post',
        body: 'article content here',
        comment: [
            {
                comment_id: 1,
                author: 'Andy',
                body: 'Comment Body'
            },
            {
                comment_id: 2,
                author: 'Joe',
                body: 'Comment from Joe'
            }
        ]
    }
]

现在我的问题是,我需要在 react 表组件中显示评论列表及其帖子。

-------------------------------------------------------------------------------
| Comment Id  |   Author         |    body              |   Post              |
-------------------------------------------------------------------------------
| 1           |   Andy           |    Comment Body      |   Title of Post     |  
| 2           |   Joe            |    Comment from Joe  |   Title of Post     |  
-------------------------------------------------------------------------------

解决这个问题的最佳方法是什么?我是否需要创建一个新对象来“展平”该对象?或者有更好的方法吗?

提前致谢

最佳答案

您可以通过在渲染函数中映射如下数据来列出所有帖子:

render(){
    let posts = posts.map(post=>{
        let comments = post.comment.map(comment=>{
            return (
                <tr>
                    <td>
                        {comment.comment_id}
                    </td>
                    <td>
                        {comment.author}
                    </td>
                    <td>
                        {comment.body}
                    </td>
                    <td>
                        {post.title}
                    </td>
                </tr>
            )
        });
        return (
            <table>
                <tr>
                    <td>Comment Id</td>
                    <td>Author</td>
                    <td>Body</td>
                    <td>Post</td>
                </tr>
                {comments}
            </table>
        );
    });
    return (
        <div>
            {posts}
        </div>
    )
}

关于javascript - 响应嵌套 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42747171/

相关文章:

java - Java 中的 JSON 数组

javascript - 无法使用 GET 调用从 Node.js 获取到 React.js 的响应

javascript - 如何自动调整文本区域的大小

javascript - 我如何将功能 react 组件传递给函数?

javascript - 草率的元素设计在 Safari 中不起作用

javascript - 函数在循环后返回对象中的未定义值

javascript - 无法将对象传递给history.push()

javascript - 如何将 ruby​​ 嵌入到 JavaScript 中

javascript - 事件在replaceWith()后不会触发

java - 使用 jackson 解析包含等于 java 中的 "final"关键字的变量的 JSON 的问题