I have a table:
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 | ... |
I receive a response from the request:
{
"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",
...
}
I need to output it in this format:
{
{
"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": []
},
}
If the line contains the same values for the comment_id
andparent_id
fields, write this line to nested_comments
.
That is, for the parent comment, the fields parent_id
and reply_id
will be empty; for comments that respond to the radio comment, they are written in nested_comments
.
How do i suppose to do it:
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)
I have everything in one array, but I need to identify the parent and to it, in the nested_comments
field, enter the child commands of this parent