在javascript中返回数组和子数组

时间:2016-02-11 04:14:11

标签: javascript jquery arrays loops

没有显示带有子数组的数组的

循环。好心劝告。我能够显示第一个数组但不能显示每个数组的子数组。

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>');
   });
});

2 个答案:

答案 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++) {