function getKeys(key) {
var keys = [];
# We all the keys for which the parent is key passed in as argument
oTeamHierarchyJson.forEach(function(currentItem) {
if (currentItem.Parent === key) {
keys.push(currentItem.Key);
}
});
# For eavery matched key, call getKeys recursively and flatten the result
return [].concat.apply([key], keys.map(getKeys));
}
console.log(getKeys("10011"));
# [ '10011', '10013', '10014' ]
get hierarchical data from json
-
23-07-2023 - |
Domanda
var oTeamHierarchyJson = [
{
"Key": "10011",
"Name": "A",
"Job Title": "VP",
"children": "C",
"Parent": "1000",
"Level": "1"
},
{
"Key": "10012",
"Name": "B",
"Job Title": "VP",
"children": "D",
"Parent": "1001",
"Level": "1"
},
{
"Key": "10013",
"Name": "C",
"Job Title": "GM",
"children": "E",
"Parent": "10011",
"Level": "2"
},
{
"Key": "10014",
"Name": "D",
"Job Title": "MP",
"children": "F",
"Parent": "10013",
"Level": "3"
}
];
I want to write a function which will take a key and get all it's child recursively.
function filterJSONData(currentKey) {
//return all children recursively
}
for 10011 - return 10013, 10014
Soluzione
Altri suggerimenti
The data structure saves only the parent relation, not the child relation, which is not really suitable for traversal. There are two ways to circumvent this shortcoming:
- Process the array to have each note refer to all of its children
- Introduce a helper function which returns all children of a node
Afterwards, it is much easier to find all successors of a given node recursively.
You can build a tree from your flat data list. Following code adds recursively a property children and fills it with the children of the each node. see http://jsfiddle.net/jeromerg/234jk/
buildTree = function(array, nodeKey) {
// getNode
var node = null;
for(var i=0; i<array.length; i++) {
if(array[i].Key == nodeKey) {
node = array[i];
break;
}
}
if(node === null) {
null;
}
// fill new children property
node.childen = [];
for(var i=0; i<array.length; i++) {
if(array[i].Parent == nodeKey) {
alert("COUCOU");
node.childen.push(array[i]);
// recursive call!
buildTree(array, array[i].Key);
}
}
return node;
}
var result = buildTree(oTeamHierarchyJson, 10011);
alert(JSON.stringify(result));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow