我的SQL查询返回结果如下:
我有两个表,Users和Category,其中Category使用User表中的外键( userID )( id )。
[
{ "userTime": "14:00",
"id": 1,
"name": "Jack",
"Category.id": 11,
"Category.name": "Category1",
"Category.userID": 1
},
{
"userTime": "14:00",
"id": 1,
"name": "Jack",
"Category.id": 12,
"Category.name": "Category2",
"Category.userID": 1
}
]
但我想按如下方式显示结果:
[
{
"userTime": "14:00",
"id": 1,
"name": "Jack",
Category: [
{
id: 11,
name: "Category1",
userID: 1
},
{
id: 12,
name: "Category2",
userID: 1
}
]
}
]
我使用Tedious和Nodejs来查询SQL DB,如何通过使用nodejs或javascript来实现上述结果?
答案 0 :(得分:0)
另一种方法是使用函数Array.prototype.reduce
。
此方法使用变量group
来放置必要的属性/键来构建分组键。
var array = [{ "userTime": "14:00", "id": 1, "name": "Jack", "Category.id": 11, "Category.name": "Category1", "Category.userID": 1 }, { "userTime": "14:00", "id": 1, "name": "Jack", "Category.id": 12, "Category.name": "Category2", "Category.userID": 1 } ],
group = ['id'],
result = Object.values(array.reduce((a, c) => {
var key = group.map(g => c[g]).join('|');
(a[key] || (a[key] = {userTime: c.userTime, id: c.id, name: c.name, Category: []})).Category.push({id: c['Category.id'], name: c['Category.name'], userID: c.id});
return a;
}, {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }