循环。好心劝告。我能够显示第一个数组但不能显示每个数组的子数组。
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>');
});
});
答案 0 :(得分:1)
这是一个与您拥有的数据结构(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);
});
}
}
});
答案 1 :(得分:0)
尝试这个
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++) {