score:2

Accepted answer

Try this way. Find the group using a recursive method and collect leaf nodes using another recursive method.

function getLeafNodes(leafNodes, obj){
    if(obj.children){
        obj.children.forEach(function(child){getLeafNodes(leafNodes,child)});
    } else{
        leafNodes.push(obj);
    }
}

function findIds(json,name){ 
   if(json.children){       
        if(json.name==name)  {
           var leafNodes = [];   
           getLeafNodes(leafNodes,json);
           console.log(leafNodes.map(function(leafNode){ return leafNode.id; })); //Logs leaf node ids to the console
        } else {
           json.children.forEach(function(child){                               
              findIds(child,name);
           });      
        }   
   }
}

Execution of following code will print ["014", "288", "223", "244"]

findIds(actualJSON,"group110");

score:0

The following code traverses the tree recursively. If param has children, then its children will be traversed. Otherwise, its id will be appended to the results array, thus, at the end results will contain the id of the leaves. getResults returns results to simplify its usage.

var results = [];

function getResults(param) {
    if (!!param.children) {
        for (var child in param.children) {
            getResults(param.children[child]);
        }
    } else {
        results[results.length] = param.id;
    }
    return results;
}

score:0

Here is a generic terse recursive answer for finding nodes using some jquery ($.map). Watch out for stack overflows if the data is deep though! Also it will not continue searching inside a matching node for more matching sub nodes, so it's only applicable if the search term does not nest logically. This method makes use of the array flattening feature of $.map.

var found = (function walk(obj, searchKey, searchTerm) {
   if(!$.isPlainObject(obj)) return null; 
   return obj[searchKey] === searchTerm ? [obj] : $.map(obj, function (lev) { 
       return walk(lev, searchKey, searchTerm); 
   }); 
})(data, 'name', 'group110');

Expanding on that to solve the specific problem above...

var found = (function walk(obj, searchTerm) { 
   if(!$.isPlainObject(obj)) return null;
   return obj.name == searchTerm 
            ? $.map(obj.children, function(c){ 
                  return $.map(c.children, function(f){ return f.id; }); })
            : $.map(obj.children, function (lev) { 
                  return walk(lev, searchTerm); }); 
})(data, 'group110');

Or rather

var found = (function walk(obj, lambda, term) { 
   if(!($.isPlainObject(obj) || $.isArray(obj))) return null;
   return lambda.call(obj, term) 
            ? $.map(obj.children, function(c){ 
                  return $.map(c.children, function(f){ return f.id; }); })
            : $.map(obj.children, function (lev) { 
                  return walk(lev, searchTerm); }); 
})(data, function(a){ return this.name == a; }, 'group110');

Related Query

More Query from same tag