user5147795
user5147795

Reputation:

get all child nodes from json

I have the following json:

    var source=[{'k':'01'},
                {'k':'02', 'children': [
                    {'k':'05'},
                    {'k':'06', 'children': [
                        {'k':'ABC'},
                        {'k':'PQR'}
                    ]},
                    {'k':'07'}
                ]},
                {'k':'03'}];

I want to be able to specify a value for k and get back all of the children (and grandchildren and great-grandchildren, etc.).

For instance if I provide '02', I want to receive

            [
              {'k':'05'},
              {'k':'06'},
              {'k':'ABC'},
              {'k':'PQR'},  
              {'k':'07'}
            ]

Upvotes: 4

Views: 16984

Answers (5)

cjhveal
cjhveal

Reputation: 5791

Try the following:

function mergeChildren(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;
}

function findChildrenForK(sources, k) {
  for (var index in sources) {
    var source = sources[index];
    if (source.k === k) {
       if (source.children) {
         return mergeChildren(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.

Upvotes: 2

Md Ashaduzzaman
Md Ashaduzzaman

Reputation: 4038

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 in source){
    if(source[index].k == input){
        if(source[index].hasOwnProperty('children')){
            console.log(source[index]); 
        }
    }
}

jsFiddle

Upvotes: 0

Jan.J
Jan.J

Reputation: 3080

Try this function:

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

Upvotes: 0

atinder
atinder

Reputation: 2090

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

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

  return false;
}

Upvotes: 1

jkyadav
jkyadav

Reputation: 1282

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

        });

Upvotes: 0

Related Questions