2

I am trying to create a string of the artist's names from the artists array shown below (i.e. "Taylor Swift, Rihanna, Justin Timberlake"), but the artist_obj is undefined and I get the error "TypeError: Cannot read property 'name' of undefined". How do I fix this?

enter image description here

Code

 //Get info for each song
var artists = item["artists"],
artist = "";
var artists_count = 0;

 artists.forEach(function(item) {
      var artist_obj = item["artists_count"];
      if(artists_count !== 0) {
           artist = artist + ", " + artist_obj["name"];
      } else {
           artist += artist_obj["name"];
      }
      artists_count++;
 });
2
  • Can you put your code somewhere we can test it? Commented Apr 9, 2017 at 6:56
  • 1
    Without going to far into your code, when you do:var artists = item["artists"], artist = ""; It would set your artists array to null, so everything you try to get from it would return undefined. Commented Apr 9, 2017 at 6:58

3 Answers 3

3

In your code you are accessing current object using index as item["artists_count"]. This wont work beacuase "artists_count" is a string & wont pass the varible value! You have to use item[artists_count] whichout double quotes to pass the variable! Apart from this you code is okay!

And please note that the argument, (i.e. item) you are passing to the forEach is the reference to the current object, thus there is no need to keep a separate variable to maintain & manually iterate the index.

Change your code to:

var artists = item["artists"],
artist = "";
var artists_count = 0; 

artists.forEach(function(item) {
      var artist_obj = item;
      if(artists_count !== 0) {
           artist = artist + ", " + artist_obj["name"];
      } else {
           artist += artist_obj["name"];
      }
      artists_count++;
 });

A more clean version is:

var artists = item["artists"],
artist = "";
artists.forEach(function(item) {
     artist = artist + item["name"] + ", ";
});
artist = artist.replace(/,\s*$/, "");
Sign up to request clarification or add additional context in comments.

Comments

0

but I think your issue is on this line artist = artist + ", " + artist_obj["name"];

On the first definition the bolded artist should be undefined. What do you want artist to be at that point? I apologize I can't add a comment since I'm new to Stack Overflow and you have to have a rep of 50 points.

1 Comment

Which is why you can answer questions for real until you have 50 rep
0

You can try this:

let list = [];
let artist_count = 0;

artists.map(artist => {
    list.push(artist.name)
    artist_count ++;
});

list.join(',');

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.