When i joining 2 tables i have to get result as nested array how can i do it in nodejs with mysql2
if i am executing
SELECT users.id as user_id , users.name as user_name , comments.id as comment_id , comments.comment as comment FROM users LEFT JOIN comments ON comments.user_id = users.id WHERE users.id = 1
I'm getting result as
[{
"user_id" : 1,
"user_name" : "Naaban"
"comment_id" : "2",
"comment" : "Hello"
},
{
"user_id" : 1,
"user_name" : "Naaban"
"comment_id" : "3",
"comment" : "Bye"
}]
My Expectation is
{
"user_id" : 1,
"user_name" : "ramesh",
"comments" : [
{
"comment_id" : 2,
"comment" : "Hello"
},
{
"comment_id" : 3,
"comment" : "Bye"
}]
}
Well you can do that directly from the query however you can normalize your code as follows:
let data = [{ user_id : 1, user_name : "Naaban", comment_id : "2", comment : "Hello" }, { user_id : 1, user_name : "Naaban", comment_id : "3", comment : "Bye" }]; let normalizedData = []; for(let i = 0; i < data.length; i++){ const comment = {comment_id: data[i].comment_id, comment: data[i].comment}; const { user_id, user_name} = data[i]; normalizedData.push({ user_id, user_name, comment }); } console.log(normalizedData);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.