How can I access a property of an object in JavaScript?

Viewed 33

So this is probably a dumb question, but I am new to JavaScript and didn't manage to find an answer anywhere else.

I am trying to get the title and artist from a spotify url. I do this by using 2 api's: Isomorphic Unfetch and spotify-url-info.

This is my code:

getPreview(url).then(data => console.log(data))

and when i run that code it displays this:

{
  date: '1961-10-20T00:00:00.000Z',   
  title: "Can't Help Falling in Love",
  type: 'track',
  track: "Can't Help Falling in Love",
  description: undefined,
  artist: 'Elvis Presley',
  image: 'https://i.scdn.co/image/ab67616d0000b273f96cefb0197694ad440c3314',
  audio: 'https://p.scdn.co/mp3-preview/5b97db904e564c1b7d140ef45cb83b1da4233d17',
  link: 'https://open.spotify.com/track/44AyOl4qVkzS48vBsbNXaC',
  embed: 'https://embed.spotify.com/?uri=spotify:track:44AyOl4qVkzS48vBsbNXaC'
}

But now my question is, how do I extract the title and artist to a seperate variable so I could use the data?

1 Answers

you could do

const {title, artist} = data

that would get you two different variables. one containing the artist and the other one containing the title, as long as their keys match the data object;

or you could do

const music = {title: data.title, artist: data.artist}

that will create a new object with the title, and track. like so:

{
  title: "can't help falling in love",
  artist: "Elvis Presley"
}

but you can absolutely use their data without destructuring, like I did before, you can use data.artist and so on. for example:

console.log(data.artist) //"Elvis Presley"
Related