我正在使用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"
}
]
我需要做的是将其分解为“季节”对象数组,如下所示:
[
{
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"}
]
}
]
按顺序,“项目”是季节对象的子级集合。
我正在寻找最简单的方法。 Lodash对我可用。
答案 0 :(得分:3)
您可以使用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))