Javascript object with array

JSON Data

My code so far:

    recentTracks.items.map(item => {
        res.push({
            trackName: item.track.name,
            artistNames: item.track.artists.map(artist=>
                {
                    console.log(artist.name);
                    return // not sure what to do here
                })
        })
    })

res is the object and for each artist.name, I want to push it into the array but I’m not sure how.

2 thoughts on “Javascript object with array”

  1. You seem to be close there. Hard to tell what’s inside item.track.artists, but let’s assume there is a name attribute that stores the artist’s name. Then do this:

        const res = [];
        recentTracks.items.map(item => {
            res.push({
                trackName: item.track.name,
                artistNames: item.track.artists.map(artist => artist.name)
            })
        })
    

    You can even shorten it a little further:

    const res = recentTracks.items.map(item => {
            return {
                trackName: item.track.name,
                artistNames: item.track.artists.map(artist => artist.name)
            }
        })
    
    Reply
  2.     recentTracks.items.map(item => {
        res.push({
            trackName: item.track.name,
            artistNames: item.track.artists.map(artist => artist.name)
        })
    })
    
    Reply

Leave a Comment