I have json array like this:
{"error":false,
"message":"",
"Album_list":[{"Album":{"id":"27","user_id":"46","title":"Internal","status":"1","time":"","created":"2016-05-02 17:20:27","modified":"2016-05-02 17:20:27"}},
{"Album":{"id":"30","user_id":"46","title":"efdrhty","status":"1","time":"","created":"2016-05-04 08:52:12","modified":"2016-05-04 08:52:12"}},
{"Album":{"id":"37","user_id":"46","title":"external","status":"1","time":"","created":"2016-05-06 08:04:55","modified":"2016-05-06 08:04:55"}},
{"Album":{"id":"38","user_id":"46","title":"James Jobs" ,"status":"1","time":"","created":"2016-05-17 09:40:41","modified":"2016-05-17 09:40:41"}},
{"Album":{"id":"41","user_id":"46","title":"17th May 2016","status":"1","time":"","created":"2016-05-17 10:20 :10","modified":"2016-05-17 10:20:10"}}]}
Now, in success function i need this Album_list data in a loop.
I try this but i can't get it correctly
Javascript code:
success: function (response) {
if (response.error == true) {
console.log(response.message);
} else {
content += '<div class="ui-grid-b gallery-sec">';
for (img in response.Album_list) {
console.log(img);
content += '<div class="ui-block-b gallery-sec">' +
'<div class="gallery-thumb-col">' +
'<div class="gallery-thumb">' +
'<img src="images/blue-box-logo.png" alt="">' +
'</div>' +
'<div class="full">' +
'<h2>'+img.Album.title+'</h2>' + //I need the title of album here
'</div>' +
'<p>2 Photos</p>' +
'<div class="ftr-bg">' +
'<i class="fa fa-trash-o" aria-hidden="true"></i></div>' +
'</div>' +
'</div>';
}
content += '</div>';
$('#gallery .page-content').html(content);
}
}
console.log(img); gives 0, then 1, then upto 4. but i need Album array here.
3 Answers 3
Use this:
for (var i = 0; i < response.Album_list.length; i++) {
var album = response.Album_list[i];
console.log(album);
}
Documentation about for in loop
Since I saw you're using jQuery. You can do this:
$.each(response.Album_list, function(index, album) {
console.log(album);
});
answered May 20, 2016 at 6:20
Haagenti
8,1945 gold badges41 silver badges53 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Poonam
You're awesome. keep it up.
Replace
for (img in response.Album_list) {
// code here
}
with
response.Album_list.forEach(function (img) {
// code here
});
Because your img is not an element, but the variable for the index.
answered May 20, 2016 at 6:23
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
1 Comment
Haagenti
forEach is not supported in all browser though. But I think it is cleaner so if possible use it.
You could also try :
for (var index in response.Album_list) {
img = response.Album_list[index];
// rest of the code as it it
}
answered May 20, 2016 at 6:26
Dhananjaya Kuppu
1,3329 silver badges10 bronze badges
default
Albumarray