假设我有一个 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/