Reputation: 72682
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.
Upvotes: 0
Views: 490
Reputation: 385194
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']);
}
Upvotes: 1
Reputation: 60580
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);
}
Upvotes: 2
Reputation: 14327
You should use
console.log(data[tracklist].name);
instead of
console.log(tracklist.name);
Upvotes: 3