Get All Child Nodes From Json
Solution 1:
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;
}
Solution 2:
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.
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:
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 || []);
}, []);
}
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 in source){
if(source[index].k == input){
if(source[index].hasOwnProperty('children')){
console.log(source[index]);
}
}
}
Post a Comment for "Get All Child Nodes From Json"