Reputation: 73
loop for array with sub arrays is not showing. Kindly advice. i am able to show the first array set but not able to show sub arrays of each set.
var json = [{
"Friends":[
{
'image' : '_assets/images/users/01.jpg',
'unread' : '22',
'name' : 'Salman Razak',
'message' : 'way to be happy...',
'lastchat' : '16th Feb 2015 | 9:30 pm'
},
{
'image' : '_assets/images/users/02.jpg',
'unread' : '22',
'name' : 'Shahid Saeed',
'message' : 'way to be happy...',
'lastchat' : '16th Feb 2005 | 9:30 pm'
}
],
"Colleagues":[
{
'image' : '_assets/images/users/02.jpg',
'unread' : '22',
'name' : 'Hyder Memon',
'message' : 'way to be happy...',
'lastchat' : '16th Feb 2015 | 9:30 pm'
}
]
}];
$.each(json, function () {
$.each(this, function (name, value) {
console.log(name + '=' + value);
$('ul').append('<li>'+ name + ', ' + json[name].join() +'</li>');
});
});
Upvotes: 0
Views: 90
Reputation: 1596
try this one
for (var i = 0, j = json.length; i < j; i++) {
Object.keys(json[i]).forEach(function(elem, index, arr){
for (var k = 0; k < json[i][elem].length; k++) {
console.log(json[i][elem][k].image);
console.log(json[i][elem][k].unread);
console.log(json[i][elem][k].name);
console.log(json[i][elem][k].message);
console.log(json[i][elem][k].lastchat);
}
});
}
// THIS LINE TO ITERATE THE MAIN ARRAY 'JSON'
for (var i = 0, j = json.length; i < j; i++) {
// THIS LINE TO GET KEYS OF json[i]......(Friends AND Colleagues FOR FIRST ELEMENT OF json)
Object.keys(json[i]).forEach(function(elem, index, arr){
//EACH KEY IS ANY ARRAY. THIS LINE TO ITERATE THE ELEMENTS OF EACH KEY
for (var k = 0; k < json[i][elem].length; k++) {
Upvotes: 0
Reputation: 1657
Here is a loop that works with the data structure you have (working jsbin)
json.forEach(function(item){
for(var group in item){
if(item.hasOwnProperty(group)){
var groupItems = item[group];
groupItems.forEach(function(person){
console.log(group, person.name);
});
}
}
});
Upvotes: 1