0
{
 "name": "Max",
 "value": 107,
 "children": [
  {
   "name": "Don",
   "value": 60,
   "children" [
     {"name": "CC", "value": 25},
     {"name": "Jim", "value": 35}
     ]
     },
  {
   "name": "David",
   "value": 47,
   "children": [
       {"name": "Jeff", "value": 32},
       {"name": "Buffy", "value": 15}
    ]
   }
  ]
 }

您如何计算该组的孩子?

data.children.length;

似乎不起作用。(数据设置为等于js)

4

1 回答 1

1

你想要的是一棵树的叶子数量。您可以递归地遍历树来做到这一点:

getNumberOfLeaves = function (obj) {
    if (obj.children) {
        var res = 0; 
        obj.children.forEach(function(d){res+=getNumberOfLeaves(d)})
        return res
    }else {
        return 1
    }
}

jsFiddle:http: //jsfiddle.net/chrisJamesC/PVhUn/

于 2013-07-02T17:19:37.847 回答