Javascript 反应嵌套json
假设我有一个JSON对象,如:Javascript 反应嵌套json,javascript,json,reactjs,Javascript,Json,Reactjs,假设我有一个JSON对象,如: posts = [ { id: '1', title: 'Title of Post', body: 'article content here', comment: [ { comment_id: 1, author: 'Andy', body: 'Comment Body
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 |
-------------------------------------------------------------------------------
最好的方法是什么?是否需要创建新对象来“扁平”对象?还是有更好的方法
提前感谢我将创建一个通用的
表
组件,它将接受列作为子项,并将数据解释到表行中,在您的例子中是注释
数组。它的用法如下(总体思路):
posts.title}>
每个列都将根据给定的
属性
键获取其数据,并在其父列的数据
属性中查找。您还可以在列
组件中提供所需的customProperty
,例如在您的情况下,所需的数据需要从范围之外传递到表
组件的值。(这样,您还可以为各种更复杂的类型(如工具提示或图标等)传递其他React组件)我将创建一个通用的表组件,该组件将接受列作为子项和数据,这些列和数据将被解释到表行中,在您的示例中是注释数组。它的用法如下(总体思路):
posts.title}>
每个列都将根据给定的属性
键获取其数据,并在其父列的数据
属性中查找。您还可以在列
组件中提供所需的customProperty
,例如在您的情况下,所需的数据需要从范围之外传递到表
组件的值。(这样,您还可以为各种更复杂的类型(如工具提示或图标等)传递其他React组件)您可以通过在渲染函数中映射以下数据来列出所有帖子:
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>
)
}
render(){
让posts=posts.map(post=>{
let comments=post.comment.map(comment=>{
返回(
{comment.comment_id}
{comment.author}
{comment.body}
{post.title}
)
});
返回(
注释Id
作者
身体
邮递
{评论}
);
});
返回(
{posts}
)
}
通过在渲染函数中映射如下数据,可以列出所有帖子:
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>
)
}
render(){
让posts=posts.map(post=>{
let comments=post.comment.map(comment=>{
返回(
{comment.comment_id}
{comment.author}
{comment.body}
{post.title}
)
});
返回(
注释Id
作者
身体
邮递
{评论}
);
});
返回(
{posts}
)
}
我强烈鼓励OP和您自己在构建其组件时采取更可重用的方法。在下次他需要构建一个表时,上面的答案将不会有帮助。我强烈建议OP和你自己在构建他/你的组件时采取一种更可重用的方法。当他下次需要建立一个表时,上面的答案将证明是没有帮助的。