user3763875
user3763875

Reputation: 329

Formatting JSON data retrieved from PostgreSql database

I am trying to display my seed data as JSON when a user visits a certain endpoint. I have two tables, Playlists and Favorites. It is a one to many relationship where a Playlist has many Favorites. The JSON should be formatted like this:

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

The function that I am calling to retrieve data from the database is this:

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

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

module.exports = getAll;

And what I get back when I call this function is this:

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

I have no idea how to format my JSON data to get it like the code up top. Any help would be greatly appreciated.

Upvotes: 0

Views: 172

Answers (1)

Code Maniac
Code Maniac

Reputation: 37755

You can use reduce

Here idea is

  • On op object create keys based on playlist id.
  • If there's already a key we push the new value to favourites
  • If not than we initialize favourites with {id, playlist_name , favourites:[]} and than push the new value

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

Upvotes: 1

Related Questions