Javascript LEFT OUTER JOIN查询结果的转换
Javascript Conversion of LEFT OUTER JOIN Query Result
我正在使用 node-postgres 检索 LEFT OUTER 连接查询的结果:
SELECT S.SEASON_ID, S.SEASON_NAME, I.ITEM_NAME, I.NOTE FROM T_SEASON S LEFT OUTER JOIN T_ITEM I ON S.SEASON_ID = I.SEASON_ID;
结果集将如下所示:
[
{
season_id:1,
season_name: "season 1",
item_name:"item1",
item_note: "text"
},
{
season_id:1,
season_name: "season 1",
item_name:"item2",
item_note: "text"
},
{
season_id:2,
season_name: "season 2",
item_name:"item3",
item_note: "text"
}
]
我需要做的是将其分解为 "season" 个对象的数组,如下所示:
[
{
seasonId: 1,
season_name: "season 1",
items: [
{item_name: "item1", item_note: "text"},
{item_name: "item2", item_note: "text"}
]
},
{
seasonId: 2,
season_name: "season2",
items: [
{item_name: "item3", item_note: "text"}
]
}
]
换句话说,"item" 是季节对象的子集合。
我正在寻找执行此操作的最简单方法。我可以使用 Lodash。
您可以使用reduce
根据season_id
创建密钥。检查键是否存在,而不是在该特定键的项目中推送值,如果不存在,则创建具有适当值的新键。最后只需从对象中取出值即可获得所需的输出。
let data = [{season_id:1, season_name: "season 1", item_name:"item1", item_note: "text"}, {season_id:1, season_name: "season 1", item_name:"item2", item_note: "text"}, {season_id:2, season_name: "season 2", item_name:"item3", item_note: "text"}]
let output = data.reduce(( op, {season_id, item_name, item_note, season_name }) => {
if(op[season_id]){
op[season_id].items.push({item_name,item_note})
} else {
op[season_id] = {
season_id,
season_name,
items: [{item_name,item_note}]
}
}
return op
},{})
console.log(Object.values(output))
我正在使用 node-postgres 检索 LEFT OUTER 连接查询的结果:
SELECT S.SEASON_ID, S.SEASON_NAME, I.ITEM_NAME, I.NOTE FROM T_SEASON S LEFT OUTER JOIN T_ITEM I ON S.SEASON_ID = I.SEASON_ID;
结果集将如下所示:
[
{
season_id:1,
season_name: "season 1",
item_name:"item1",
item_note: "text"
},
{
season_id:1,
season_name: "season 1",
item_name:"item2",
item_note: "text"
},
{
season_id:2,
season_name: "season 2",
item_name:"item3",
item_note: "text"
}
]
我需要做的是将其分解为 "season" 个对象的数组,如下所示:
[
{
seasonId: 1,
season_name: "season 1",
items: [
{item_name: "item1", item_note: "text"},
{item_name: "item2", item_note: "text"}
]
},
{
seasonId: 2,
season_name: "season2",
items: [
{item_name: "item3", item_note: "text"}
]
}
]
换句话说,"item" 是季节对象的子集合。
我正在寻找执行此操作的最简单方法。我可以使用 Lodash。
您可以使用reduce
根据season_id
创建密钥。检查键是否存在,而不是在该特定键的项目中推送值,如果不存在,则创建具有适当值的新键。最后只需从对象中取出值即可获得所需的输出。
let data = [{season_id:1, season_name: "season 1", item_name:"item1", item_note: "text"}, {season_id:1, season_name: "season 1", item_name:"item2", item_note: "text"}, {season_id:2, season_name: "season 2", item_name:"item3", item_note: "text"}]
let output = data.reduce(( op, {season_id, item_name, item_note, season_name }) => {
if(op[season_id]){
op[season_id].items.push({item_name,item_note})
} else {
op[season_id] = {
season_id,
season_name,
items: [{item_name,item_note}]
}
}
return op
},{})
console.log(Object.values(output))