0

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.

2
  • 1
    What is the actual result you want? Not just format Commented Mar 24, 2019 at 3:40
  • 1
    How can playlist_id = 1 have two different name ("chill_tunes" and "good_vibes")? Commented Mar 24, 2019 at 3:41

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.