【发布时间】:2019-02-28 12:25:38
【问题描述】:
我有一张桌子:
comment_id | user_Id | product_id | parent_id | reply_id | ... |
--------------------------------------------------------------------
1 | 20 | 1 | null | null | ... |
2 | 20 | 1 | null | null | ... |
3 | 7 | 1 | 1 | 1 | ... |
4 | 7 | 1 | 1 | 2 | ... |
5 | 7 | 1 | null | null | ... |
6 | 7 | 1 | null | null | ... |
7 | 7 | 1 | 2 | 2 | ... |
我收到请求的响应:
{
"comment_id": 1,
"user_id": 20,
"product_id": 1,
"parent_id": null,
"reply_id": null,
...
},
{
"comment_id": 2,
"user_id": 20,
"product_id": 1,
"parent_id": null,
"reply_id": null,
...
},
{
"comment_id": 3,
"user_id": 7,
"product_id": 1,
"parent_id": "1",
"reply_id": "1",
...
},
{
"comment_id": 4,
"user_id": 7,
"product_id": 1,
"parent_id": "1",
"reply_id": "2",
...
},
{
"comment_id": 5,
"user_id": 7,
"product_id": 1,
"parent_id": null,
"reply_id": null,
...
},
{
"comment_id": 6,
"user_id": 7,
"product_id": 1,
"parent_id": null,
"reply_id": null,
...
},
{
"comment_id": 7,
"user_id": 7,
"product_id": 1,
"parent_id": "2",
"reply_id": "2",
...
}
我需要以这种格式输出:
{
{
"comment_id": 1,
"user_id": 20,
"product_id": 1,
"parent_id": null,
"reply_id": null,
...,
"nested_comments": [
{
"comment_id": 3,
"user_id": 7,
"product_id": 1,
"parent_id": "1",
"reply_id": "1",
...
},
{
"comment_id": 4,
"user_id": 7,
"product_id": 1,
"parent_id": "1",
"reply_id": "2",
...
}
]
},
{
"comment_id": 2,
"user_id": 20,
"product_id": 1,
"parent_id": null,
"reply_id": null,
"user_name": "Nikita Velichkin",
...,
"nested_comments": [
{
"comment_id": 7,
"user_id": 7,
"product_id": 1,
"parent_id": "2",
"reply_id": "2",
...
}
]
},
{
"comment_id": 5,
"user_id": 7,
"product_id": 1,
"parent_id": null,
"reply_id": null,
...,
"nested_comments": []
},
{
"comment_id": 6,
"user_id": 7,
"product_id": 1,
"parent_id": null,
"reply_id": null,
...,
"nested_comments": []
},
}
如果该行包含comment_id 和parent_id 字段的相同值,则将此行写入nested_comments。
即对于父评论,字段parent_id和reply_id将为空;回复电台评论的cmets,写在nested_comments。
我想怎么做:
let comments = data_comments.rows; // I write down the answer from the server
for (let i = 0; i < comments.length; i++) {
comments[i].nested_comments = []; // where to write the creation of fields
if (comments[i].comment_id === comments[i].parent_id) { //field alignment
comments[i].nested_comments.push(comments[i]); // field entry
}
}
console.log(comments)
我将所有内容都放在一个数组中,但我需要识别父级并在 nested_comments 字段中输入该父级的子命令
【问题讨论】:
-
parent_id和reply_id有什么关系? (在层次结构方面)。另外 - 您希望以多少层级结束? -
在
reply_id中,有一个`comment_id` 被回答,parent_id指定他们将传递给哪个父级。一层嵌套将是。
标签: javascript node.js