简体   繁体   中英

Javascript Conversion of LEFT OUTER JOIN Query Result

I am using node-postgres to retrieve the results of a LEFT OUTER join query:

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;

The resultset is going to look like this:

[
 {
   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"
 }
]

What I need to do is break this into an array of "season" objects as follows:

[
 {
   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"}
   ]
 }
]

In order words, "item" is a child collection of a season object.

I'm looking for the easiest way to do this. Lodash is available to me.

You can use reduce

Create a key based on season_id . check if the key if it exists than push value in items of that particular key if not than create a new key with appropriate values. At the end just take the values out of object to get desired output.

 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)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM