JSON计算每个孩子的子孙数

时间:2014-11-17 06:10:36

标签: javascript jquery json

我有一个json数据,我想得到孩子和大孩子的数量。

我试过这个但是我无法得到每个孩子的大孩子数量:

JSON

var data = {  "members":[  
  {  
     "user_id":3961,
     "parent_id":3895,
     "first_name":"No",
     "last_name":"Ah",
     "avatar_url":null,
     "sub_members":[  
        {  
           "user_id":3965,
           "parent_id":3895,
           "first_name":"Uncle",
           "last_name":"Bear",
           "avatar_url":null,
           "sub_members":[  
              {  
                 "user_id":3957,
                 "parent_id":3956,
                 "first_name":"Child1",
                 "last_name":"Bear",
                 "avatar_url":null
              },
              {  
                 "user_id":3957,
                 "parent_id":3956,
                 "first_name":"Child2",
                 "last_name":"Bear",
                 "avatar_url":null
              },
              {  
                 "user_id":3957,
                 "parent_id":3956,
                 "first_name":"Child3",
                 "last_name":"Bear",
                 "avatar_url":null
              }
           ]
        }
     ]
  }]}; 

JQUERY

var count = 0;

  for ( property in data.members[0].sub_members ){
      if(data.members[0].sub_members.hasOwnProperty(property)){
          count++;
      }
  }
  console.log("total child  = " + count);

非常感谢任何帮助。提前谢谢!

1 个答案:

答案 0 :(得分:1)

试试这个。

 var total=0;
 var countChildren=function(data,num){
      if(data.sub_members&&data.sub_members.length){
         var len=data.sub_members.length;
         num+=len;
         for(var i=0;i<len;i++){
            countChildren(data.sub_members[i],num);
         }
      }
      return false;
 }
 countChildren(data.members,total);