In node js I get flat data from the db. I want to group the data by the main entity.
Example of data that getting from the db (using left join query)
[
{
writer_id:1,
writer_name:'Ben'
book_id:1
book_name:'The special book'
},
{
writer_id:1,
writer_name:'Ben'
book_id:2
book_name:'My second book'
}
]
I need to format the data like this
[{
writer_id:1,
writer_name:'Ben'
books:
[{book_id:1
book_name:'The special book'
},{book_id:2
book_name:'My second book'
}]
}]
How can I do it using javascript or using knex queries (if it possible)
my code:
return db.from('arrangement')
.innerJoin('users as u1', 'arrangement.user_id', 'u1.id')
.....
.leftJoin('commercial_papers_status', 'commercial_papers.status_id', 'commercial_papers_status.id')
.select(['commercial_papers.*', ......)
.where({
'commercial_papers.user_id': user.id,
'commercial_papers.deleted':0
})
.then((arrangements) => {
*************************
TEST FOR GROUPING
************************
result = arrangements.reduce(function (r, obj) {
if(obj.id){
key ='key' + obj.id || '0';
r[key] = r[key] || [];
let {id, price, ...rest} = obj;
//console.log(rest); // { c: 30, d: 40 }
r[key].push(rest);
}
return r;
}, Object.create(null));
return result