0

I'm using the following code to make an AJAX call:

  $.ajax({
    url: href,
    type: 'POST',
    data: {},
    dataType: "json",
    error: function(req, resulttype, exc)
    {
      // do error handling
    },
    success: function(data)
    {
      for (var tracklist in data) {
        console.log(tracklist.name); // undefined
        console.log(tracklist['name']); // undefined
      }
    }
  });

What I return to the AJAX request is:

{"5":{"id":5,"name":"2 tracks","count":2},"4":{"id":4,"name":"ddddd","count":1},"7":{"id":7,"name":"Final test","count":2}}

What I would like to know is how to access the name attribute of the current tracklist.

0

3 Answers 3

3

You should use

console.log(data[tracklist].name);

instead of

console.log(tracklist.name);
Sign up to request clarification or add additional context in comments.

Comments

2

If you want to iterate over those objects, it would be better if you returned an array:

[{"id":5,"name":"2 tracks","count":2},{"id":4,"name":"ddddd","count":1},{"id":7,"name":"Final test","count":2}]

Then, you could use a for-loop similar to what you were trying:

  for (var tracklist in data) {
    console.log(data[tracklist].id);
    console.log(data[tracklist].name);
  }

Comments

1

In the loop:

for (var tracklist in data) {
  console.log(tracklist.name); // undefined
  console.log(tracklist['name']); // undefined
}

tracklist is the key of each element, not its value.

Thus:

for (var tracklist in data) {
  console.log(data[tracklist].name); // ... or ...
  console.log(data[tracklist]['name']);
}

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.