格式化从PostgreSql数据库检索的JSON数据

时间:2019-03-24 03:38:19

标签: javascript node.js express knex.js

当用户访问某个端点时,我试图将我的种子数据显示为JSON。我有两个表,播放列表和收藏夹。这是一对多关系,其中播放列表具有许多收藏夹。 JSON的格式应如下:

[{
    "id": 1,
    "playlist_name": "Favorite songs of all time",
    "favorites": [{
        "id": 1,
        "name": "We Will Rock You",
        "artist_name": "Queen",
        "genre": "Rock",
        "rating": 88
    }]
}]

我要从数据库中检索数据的函数是这样的:

const connection = require("../connection");

function getAll() {
  return connection.select().from('playlists').join('favorites', 'playlists.id', '=', 'favorites.id')
}

module.exports = getAll;

当我调用此函数时,我得到的是:

[
  {
    "id": 1,
    "playlist_name": "chill_tunes",
    "name": "Leo",
    "artist_name": "John",
    "genre": "Pop",
    "rating": 42,
    "playlist_id": 1
  },
  {
    "id": 2,
    "playlist_name": "good_vibes",
    "name": "Dan",
    "artist_name": "Deer",
    "genre": "Rock",
    "rating": 52,
    "playlist_id": 1
  },
  {
    "id": 3,
    "playlist_name": "hump_day_happiness",
    "name": "Nick",
    "artist_name": "Legend",
    "genre": "Rap",
    "rating": 12,
    "playlist_id": 2
  }
]

我不知道如何格式化JSON数据以使其像上面的代码一样。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您可以使用reduce

这里的想法是

  • op对象上,根据播放列表ID创建密钥。
  • 如果已经有键,我们会将新值推入favourites
  • 如果不是,我们用favourites初始化{id, playlist_name , favourites:[]},然后推送新值

let arr = [{"id": 1,"playlist_name": "chill_tunes","name": "Leo","artist_name": "John","genre": "Pop","rating": 42,"playlist_id": 1},{"id": 2,"playlist_name": "good_vibes","name": "Dan","artist_name": "Deer","genre": "Rock","rating": 52,"playlist_id": 1},{"id": 3,"playlist_name": "hump_day_happiness","name": "Nick","artist_name": "Legend","genre": "Rap","rating": 12,"playlist_id": 2}]

let final = arr.reduce((op,{id, playlist_name ,name ,artist_name ,genre ,rating , playlist_id}) => {
  op[playlist_id] = op[playlist_id] || {id, playlist_name , favourites:[]}
  op[playlist_id].favourites.push({id, playlist_id ,name ,artist_name ,genre ,rating})
  return op
},{})

console.log(Object.values(final))