Skip to content Skip to sidebar Skip to footer

Get All Child Nodes From Json

I have the following json: var source=[{'k':'01'}, {'k':'02', 'children': [ {'k':'05'}, {'k':'06', 'children': [

Solution 1:

vargetChildren(key) {
  var x = source.filter(function(s){
     return s.k == key;
  });

  if( x.length && typeof x[0].children !== 'undefined') {
   return x[0].children;
  }

  returnfalse;
}

Solution 2:

Try the following:

functionmergeChildren(sources) {
  var children = [];
  for (var index in sources) {
    var source = sources[index];
    children.push({k: source.k});
    if (source.children) {
      children = children.concat(mergeChildren(source.children))
    }
  }
  return children;
}

functionfindChildrenForK(sources, k) {
  for (var index in sources) {
    var source = sources[index];
    if (source.k === k) {
       if (source.children) {
         returnmergeChildren(source.children);
       }
    }
  }
}

findChildrenForK scans through an array of objects, sources, and matches their property k to the k supplied to the function. If a matching object is found, we call mergeChildren on that object's children property.

mergeChildren iterates through the array of objects given to it, and pushes each key into an array, called children. If any objects themselves have children, we concatenate them to our children accumulator by calling mergeChildren recursively and using the Array#concat function.

See the script in action with your sample data in this JSFiddle.

Solution 3:

You can try below code.

$(document).ready(function () {
            var source = [{ 'k': '01' }, { 'k': '02', 'children': [{ 'k': '05' }, { 'k': '06' }, { 'k': '07' }] }, { 'k': '03' }];
            $.each(source, function (i, item) {
                if (item.k == "02")
                {
                    var list = item.children;
                }
            });

        });

Solution 4:

Try this function:

functiongetChildren(source, parentId) {
    return $.grep(source, function(parent) {
        // get only parents with matched idreturn parent.k === parentId;
    }).reduce(function(children, parent) {
        // sum all children into one arrayreturn children.concat(parent.children || []);
    }, []);
}

Solution 5:

You can traverse through your array matching the user input and then check if an specific element has the property you are looking for or not. Try this way,

var input = '02';

for(var index insource){
    if(source[index].k == input){
        if(source[index].hasOwnProperty('children')){
            console.log(source[index]); 
        }
    }
}

jsFiddle

Post a Comment for "Get All Child Nodes From Json"