在节点js中,我从数据库获取平面数据。 我想按主要实体对数据进行分组。
从数据库获取数据的示例(使用左联接查询)
[
{
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'
}
]
我需要像这样格式化数据
[{
writer_id:1,
writer_name:'Ben'
books:
[{book_id:1
book_name:'The special book'
},{book_id:2
book_name:'My second book'
}]
}]
如何使用javascript做到这一点 或使用knex查询(如果可能)
我的代码:
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