Related
Hi I am using JavaScript and jQuery as client side script. I am little bit new to Recursive functions. I have a JSON data as below and I have tried to make a tree structure using below JSON data by writing a recursive function but I am not able to build the tree structure.
var jsonData = { "$id": "45", "_children": [{ "$id": "46", "_children": [{ "$id": "47", "_children": [{ "$id": "48", "_children": [{ "$id": "49", "_children": null, "id": "Test1", "text": "Text1", "name": "name1", "parent": null, "root": { "$ref": "49" }, "depth": 0, "children": [] }], "id": "id1", "text": "text2", "name": "name2", "parent": null, "root": { "$ref": "48" }, "depth": 0, "children": [{ "$ref": "49" }] }], "id": "id3", "text": "text4", "name": "name4", "parent": null, "root": { "$ref": "47" }, "depth": 0, "children": [{ "$ref": "48" }] }, { "$id": "50", "_children": [{ "$id": "51", "_children": [{ "$id": "52", "_children": null, "id": "id6", "text": "text6", "name": "name6", "parent": null, "root": { "$ref": "52" }, "depth": 0, "children": [] }], "id": "id7", "text": "text7", "name": "name7", "parent": null, "root": { "$ref": "51" }, "depth": 0, "children": [{ "$ref": "52" }] }], "id": "id8", "text": "text8", "name": "name8", "parent": null, "root": { "$ref": "50" }, "depth": 0, "children": [{ "$ref": "51" }] }], "id": "id9", "text": "text9", "name": "name9", "parent": null, "root": { "$ref": "46" }, "depth": 0, "children": [{ "$ref": "47" }, { "$ref": "50" }] }, { "$id": "53", "_children": [{ "$id": "54", "_children": null, "id": "id10", "text": "text10", "name": "name10", "parent": null, "root": { "$ref": "54" }, "depth": 0, "children": [] }], "id": "id11", "text": "text11", "name": "name11", "parent": null, "root": { "$ref": "53" }, "depth": 0, "children": [{ "$ref": "54" }] }], "id": "0", "text": "0", "name": "", "parent": null, "root": { "$ref": "45" }, "depth": 0, "children": [{ "$ref": "46" }, { "$ref": "53" }] }
Required Output:
var treeNode = {
id: 101, // random
text: object.name,
icon: "fas fa-plus",
subNode: {
// id, text, icon and subNode of Children object
// recursive data, So on....
}
};
Can anyone suggest me or help me to write javascript or jQuery Recursive function based on above JSON data so I can build tree structure. I know I am asking about help because I do have less knowledge about recursive function.
If we abstract this a bit, it's pretty easy to write a general-purpose tree-mapping function. Then we can supply two callback functions: one to find the child nodes of the input and one to build the output node based on the input and the mapped children. Such a function turns out to be surprisingly simple:
const mapTree = (getChildren, transformNode) => (tree) =>
transformNode (
tree,
(getChildren (tree) || []) .map (mapTree (getChildren, transformNode))
)
For your data, getChildren is simply (node) => node._children
And the node transformation might be as simple as:
const transformNode = (node, children) =>
({
id: node.$id, // or a randomizing call?
text: node.name,
icon: "fas fa-plus", // is this really a fixed value?
subNode: children
})
Putting this together we get
const mapTree = (getChildren, transformNode) => (tree) =>
transformNode (
tree,
(getChildren (tree) || []) .map (mapTree (getChildren, transformNode))
)
const kids = (node) => node._children
const transformNode = (node, children) =>
({
id: node.$id,
text: node.name,
icon: "fas fa-plus",
subNode: children
})
const myTransform = mapTree (kids, transformNode)
const jsonData = { "$id": "45", "_children": [{ "$id": "46", "_children": [{ "$id": "47", "_children": [{ "$id": "48", "_children": [{ "$id": "49", "_children": null, "id": "Test1", "text": "Text1", "name": "name1", "parent": null, "root": { "$ref": "49" }, "depth": 0, "children": [] }], "id": "id1", "text": "text2", "name": "name2", "parent": null, "root": { "$ref": "48" }, "depth": 0, "children": [{ "$ref": "49" }] }], "id": "id3", "text": "text4", "name": "name4", "parent": null, "root": { "$ref": "47" }, "depth": 0, "children": [{ "$ref": "48" }] }, { "$id": "50", "_children": [{ "$id": "51", "_children": [{ "$id": "52", "_children": null, "id": "id6", "text": "text6", "name": "name6", "parent": null, "root": { "$ref": "52" }, "depth": 0, "children": [] }], "id": "id7", "text": "text7", "name": "name7", "parent": null, "root": { "$ref": "51" }, "depth": 0, "children": [{ "$ref": "52" }] }], "id": "id8", "text": "text8", "name": "name8", "parent": null, "root": { "$ref": "50" }, "depth": 0, "children": [{ "$ref": "51" }] }], "id": "id9", "text": "text9", "name": "name9", "parent": null, "root": { "$ref": "46" }, "depth": 0, "children": [{ "$ref": "47" }, { "$ref": "50" }] }, { "$id": "53", "_children": [{ "$id": "54", "_children": null, "id": "id10", "text": "text10", "name": "name10", "parent": null, "root": { "$ref": "54" }, "depth": 0, "children": [] }], "id": "id11", "text": "text11", "name": "name11", "parent": null, "root": { "$ref": "53" }, "depth": 0, "children": [{ "$ref": "54" }] }], "id": "0", "text": "0", "name": "", "parent": null, "root": { "$ref": "45" }, "depth": 0, "children": [{ "$ref": "46" }, { "$ref": "53" }] }
console .log (myTransform (jsonData))
This does something slightly different from your requested output. You had written subNode: { ... }, but instead I'm returning an array of objects, subNodes: [ ... ], as I don't make any real sense of a plain object here.
Also, this will yield an empty subNodes array if an input node has no children. If you would rather not have the subNodes property, you could replace
subNode: children
with something like
...(children .length ? {subNode: children} : {})
Obviously, you don't need the named helpers and could call mapTree with anonymous functions like this:
const myTransform = mapTree (
(node) => node._children,
(node, children) =>
({
id: node.$id,
text: node.name,
icon: "fas fa-plus",
subNode: children
})
)
This mapTree function was very easy to write, as I didn't have to think about any details of the output or input formats as I wrote it. But perhaps that abstraction is not helpful to me, and I'm never going to use it except here. If so, I can simply rework the abstract version by plugging the hard-coded callbacks directly. With only a little manipulation, that will turn it into this version:
const newTransform = (node) =>
({
id: node.$id,
text: node.name,
icon: "fas fa-plus",
subNode: (node._children || []).map(newTransform)
})
const jsonData = { "$id": "45", "_children": [{ "$id": "46", "_children": [{ "$id": "47", "_children": [{ "$id": "48", "_children": [{ "$id": "49", "_children": null, "id": "Test1", "text": "Text1", "name": "name1", "parent": null, "root": { "$ref": "49" }, "depth": 0, "children": [] }], "id": "id1", "text": "text2", "name": "name2", "parent": null, "root": { "$ref": "48" }, "depth": 0, "children": [{ "$ref": "49" }] }], "id": "id3", "text": "text4", "name": "name4", "parent": null, "root": { "$ref": "47" }, "depth": 0, "children": [{ "$ref": "48" }] }, { "$id": "50", "_children": [{ "$id": "51", "_children": [{ "$id": "52", "_children": null, "id": "id6", "text": "text6", "name": "name6", "parent": null, "root": { "$ref": "52" }, "depth": 0, "children": [] }], "id": "id7", "text": "text7", "name": "name7", "parent": null, "root": { "$ref": "51" }, "depth": 0, "children": [{ "$ref": "52" }] }], "id": "id8", "text": "text8", "name": "name8", "parent": null, "root": { "$ref": "50" }, "depth": 0, "children": [{ "$ref": "51" }] }], "id": "id9", "text": "text9", "name": "name9", "parent": null, "root": { "$ref": "46" }, "depth": 0, "children": [{ "$ref": "47" }, { "$ref": "50" }] }, { "$id": "53", "_children": [{ "$id": "54", "_children": null, "id": "id10", "text": "text10", "name": "name10", "parent": null, "root": { "$ref": "54" }, "depth": 0, "children": [] }], "id": "id11", "text": "text11", "name": "name11", "parent": null, "root": { "$ref": "53" }, "depth": 0, "children": [{ "$ref": "54" }] }], "id": "0", "text": "0", "name": "", "parent": null, "root": { "$ref": "45" }, "depth": 0, "children": [{ "$ref": "46" }, { "$ref": "53" }] }
console .log (newTransform (jsonData))
There's an important point here. This generic function was much easier to write than if I'd tried to write something to convert your format directly. While there is a danger in too-early abstraction, it also can offer significant benefits. I might well choose to keep only that last version, but the generic abstraction simplified the development of it.
It can be something like that, with using the json data model
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="lib/style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id="myDiv"></div>
</body>
<script>
var treeData={
"Id":"10",
"text":"Document Categories",
"icon":"fas fa-plus",
"subNode":
[
{
"Id":"11",
"text":"Pdf Documents",
"icon":"fas fa-plus",
"subNode":[
{
"Id":"31",
"text":"Book Pdfs",
"icon":"fas fa-plus",
"subNode":[]
},
{
"Id":"32",
"text":"EPub",
"icon":"fas fa-plus",
"subNode":[
{
"Id":"20",
"text":"EBook Epubs1",
"icon":"fas fa-plus",
"subNode":[]
},
{
"Id":"30",
"text":"EBook Epubs2",
"icon":"fas fa-plus",
"subNode":[]
}
]
}
]
},
{
"Id":"33",
"text":"Text Documents",
"icon":"fas fa-plus",
"subNode":[
{
"Id":"32",
"text":"Book Text",
"icon":"fas fa-plus",
"subNode":[]
},
{
"Id":"35",
"text":"Automatic Text",
"icon":"fas fa-plus",
"subNode":[]
}
]
}
]
};
var newTree = AddRecursive(null, treeData);
var treeDiv = $('#myDiv');
treeDiv.append(newTree);
function AddRecursive(tree, data) {
if (tree == null) {
tree = $('<ul/>');
tree.attr('id', 'treeID');
}
var listU = $('<ul />');
listU.addClass('ul class');
var listItem = $('<li />');
listItem.addClass('li class');
listItem.attr('data-id', data.Id);
var link = $('<a />');
var i = $('<i/>').addClass('fa fa-folder');
link.append(i);
//link.addClass("linkClass");
link.append(data.text);
listItem.append(link);
if (data.subNode.length > 0) {
var span = $(' <span />');
span.addClass('fa-chevron-down');
link.append(span);
}
listU.append(listItem);
tree.append(listU);
for (i in data.subNode) {
AddRecursive(listItem, data.subNode[i]);
}
return tree;
}
</script>
</html>
The Overall Context is to find the leaf node of every parent(x) and children(x1) if there are more than 2 leaf nodes make them the child's as one under another
I Tried to use loadash in Nodejs but I was unable to get the expected result
I have a JSON Data
{
"Id": "1",
"name": "x",
"parent": "",
"children": [{
"Id": "2",
"name": "x1",
"parent": "1",
"children": [{
"Id": "3",
"name": "x2",
"parent": "2"
}, {
"Id": "4",
"name": "x3",
"parent": "2"
},
{
"Id": "5",
"name": "x4",
"parent": "2"
},
{
"Id": "6",
"name": "x5",
"parent": "2"
},
{
"Id": "7",
"name": "x6",
"parent": "2"
},
{
"Id": "8",
"name": "x7",
"parent": "2"
}
]
},
{
"Id": "9",
"name": "x8",
"parent": "1"
},
{
"Id": "10",
"name": "x10",
"parent": "1"
}, {
"Id": "11",
"name": "x9",
"parent": "1"
},
{
"Id": "12",
"name": "x11",
"parent": "1"
}
]
}
I would like to change into the below format
{
"Id": "1",
"name": "x",
"parent": "",
"children": [{
"Id": "2",
"name": "x1",
"parent": "1",
"children": [{
"Id": "3",
"name": "x2",
"IC": "Yes",
"parent": "2",
"children": [{
"Id": "5",
"name": "x4",
"IC": "Yes",
"parent": "2",
"children": [{
"Id": "7",
"parent": "2",
"name": "x6"
}]
}]
},
{
"Id": "4",
"name": "x3",
"IC": "Yes",
"parent": "2",
"children": [{
"Id": "5",
"name": "x5",
"IC": "Yes",
"parent": "2",
"children": [{
"Id": "7",
"name": "x7",
"IC": "Yes",
"parent": "2"
}]
}]
}
]
},
{
"Id": "9",
"name": "x8",
"parent": "1",
"children": [{
"Id": "10",
"name": "x10",
"IC": "Yes",
"parent": "1"
}]
},
{
"Id": "11",
"name": "x9",
"parent": "1",
"children": [{
"Id": "11",
"name": "x11",
"parent": "1",
"IC": "Yes"
}]
}
]
}
Note:
1. If there are 8 leaf nodes it should be split 4+4,
2. If there are 9 leaf nodes it should be split 5+4,
3. In the same way, If it has 13 it can be split into 7+6.
any help would be appreciated
thanks in advance
The following code will take all leaf nodes and create 2 even branches from them. The output is not identical to yours, but you mention in your comments that the branches can be built randomly from the leaf nodes, and this code respects that requirement.
const input = {
"name": "x",
"children": [
{
"name": "x1",
"children": [
{
"name": "x2"
},
{
"name": "x3"
},
{
"name": "x4"
},
{
"name": "x5"
},
{
"name": "x6"
},
{
"name": "x7"
}
]
},
{
"name": "x8"
},
{
"name": "x10"
},
{
"name": "x9"
},
{
"name": "x11"
}
]
};
function cutLeafNodes(node){
if(!node.children){
return;
}
const leaves = [];
const branches = [];
node.children.forEach(child => {
if(child.children){
branches.push(child);
} else {
leaves.push(child);
}
});
node.children = branches;
return leaves;
}
function reorderLeaves(nodes){
if(!nodes){
return;
}
const midpoint = nodes.length / 2;
const newChildren = [];
newChildren.push(createAncestry(nodes.splice(0, midpoint)));
newChildren.push(createAncestry(nodes));
return newChildren;
}
function createAncestry(nodes){
let currentChild = nodes[0];
const firstChild = currentChild;
for (let i = 1; i < nodes.length; i++) {
currentChild.children = [nodes[i]];
currentChild = currentChild.children[0];
}
return firstChild;
}
function reorganizeTree(node){
const leaves = cutLeafNodes(node);
if(node.children){
node.children.forEach(child => {
reorganizeTree(child);
});
}
if(leaves){
const newBranches = reorderLeaves(leaves);
newBranches.forEach(branch =>{
node.children.push(branch);
})
}
return node;
}
const output = reorganizeTree(input);
console.debug(output);
I am using angular JS and one of their examples:http://jsfiddle.net/furf/EJGHX/
I need to take the data when the update function occurs and add some values to it before I send to the server. (If doing this with angular instead of js would be better let me know)
I'm trying to get the 'parentid' and the 'index' and update the children.
Here is the data I'm looping through
{
"children": [{
"id": "5",
"parentid": "0",
"text": "Device Guides",
"index": "1",
"children": [{
"id": "10",
"index": "0",
"text": "Grandstream GXP-21XX"
}, {
"id": "11",
"index": "1",
"text": "Polycom Soundstation/Soundpoint"
}, {
"id": "23",
"index": "2",
"text": "New Polycom"
}]
}, {
"id": "6",
"parentid": "0",
"text": "Pre-Sales Evaluation",
"index": "0",
"children": []
}, {
"id": "7",
"parentid": "0",
"text": "Router Setup Guides",
"index": "2",
"children": [{
"id": "9",
"index": "0",
"text": "Sonicwall"
}, {
"id": "12",
"index": "1",
"text": "Cisco"
}]
}, {
"id": "9",
"parentid": "7",
"text": "Sonicwall",
"index": "0",
"children": []
}, {
"id": "10",
"parentid": "5",
"text": "Grandstream GXP-21XX",
"index": "0",
"children": []
}, {
"id": "11",
"parentid": "5",
"text": "Polycom Soundstation/Soundpoint",
"index": "1",
"children": []
}, {
"id": "12",
"parentid": "7",
"text": "Cisco",
"index": "1",
"children": []
}, {
"id": "15",
"parentid": "0",
"text": "Post-Sales Implementation Check List",
"index": "7",
"children": [{
"id": "16",
"index": "0",
"text": "Porting and New Number Details"
}, {
"id": "18",
"index": "1",
"text": "Partner Setup"
}, {
"id": "19",
"index": "2",
"text": "test"
}, {
"id": "21",
"index": "3",
"text": "test"
}]
}, {
"id": "16",
"parentid": "15",
"text": "Porting and New Number Details",
"index": "0",
"children": []
}, {
"id": "18",
"parentid": "15",
"text": "Partner Setup",
"index": "1",
"children": []
}, {
"id": "19",
"parentid": "15",
"text": "test",
"index": "2",
"children": []
}, {
"id": "20",
"parentid": "0",
"text": "test",
"index": "11",
"children": []
}, {
"id": "21",
"parentid": "15",
"text": "test",
"index": "3",
"children": []
}, {
"id": "23",
"parentid": "5",
"text": "New Polycom",
"index": "2",
"children": []
}, {
"id": "24",
"parentid": "0",
"text": "Test Markup",
"index": "14",
"children": []
}, {
"id": "25",
"parentid": "0",
"text": "test",
"index": "15",
"children": []
}]
}
This is how I'm currently looping through it, but it only gets the first dimension
for (i = 0, l = data.length; i < l; i++) {
parentid = data[i].id == null ? '0' : data[i].id;
data[i].index = i;
if (data[i].children) {
if (data[i].children.length > 0) {
for (q = 0, r = data[i].children.length; q < r; q++) {
data[i].children[q].parentid = parentid;
data[i].children[q].index = q;
}
}
}
}
I found this one on another fiddle, but I don't know how I would grab the parentid or the index
$.each(target.children, function(key, val) { recursiveFunction(key, val) });
function recursiveFunction(key, val) {
actualFunction(key, val);
var value = val['children'];
if (value instanceof Object) {
$.each(value, function(key, val) {
recursiveFunction(key, val)
});
}
}
function actualFunction(key, val) {}
If I'm understanding you correctly, you want each 'child' to have a parentID (defined by its parent; 0 otherwise) and an index (based on its position within it sibling set).
function normalize(parent) {
if (parent && parent.children) {
for (var i = 0, l = parent.children.length; i < l; ++i) {
var child = parent.children[i];
child.index = i;
if (!child.parentId) child.parentId = parent.id || '0';
normalize(child);
}
}
}
normalize(data);
Recursion is calling function inside the same function. Your sample is not a recursion at all;
function runRecursive(input) {
for (var i = 0, l = input.length; i < l; i++) {
var current = input[i];
parentid = current.id == null ? '0' : current.id;
current.index = i;
if (current.children && current.children.length > 0) {
runRecursive(current.children);
};
};
};
runRecursive(data.children);
Also you should define i and l with var keyword, otherwise it will be located in window context and recursion logic will broken.
Though I don't get what is parentid variable for and why it defined outside visible code.
I grab a list of data from the server and I have to convert it.
Part of this is turning it into a 3 dimensional array. After the "myArr[i].children.push(temp);" it leaves copies of the objects that were pushed in the root of the array. Can I either push without copying or how would I delete these? (I have underscore js included, I know they have good array functions :))
for (var i = 0; i < myArr.length; i++) {
myArr[i].children = [];
for (var q = 0; q < myArr.length; q++) {
if (myArr[i].id == myArr[q].parentid) {
var temp = {
id: myArr[q].id,
index: myArr[q].index,
text: myArr[q].text
}
myArr[i].children.push(temp);
};
};
};
The Data
[{
"id": "5",
"parentid": "0",
"text": "Device Guides",
"index": "0"
}, {
"id": "6",
"parentid": "0",
"text": "Pre-Sales Evaluation",
"index": "1"
}, {
"id": "7",
"parentid": "0",
"text": "Router Setup Guides",
"index": "2"
}, {
"id": "9",
"parentid": "7",
"text": "Sonicwall",
"index": "0"
}, {
"id": "10",
"parentid": "5",
"text": "Grandstream GXP-21XX",
"index": "1"
}, {
"id": "11",
"parentid": "5",
"text": "Polycom Soundstation\/Soundpoint",
"index": "2"
}, {
"id": "12",
"parentid": "7",
"text": "Cisco",
"index": "1"
}, {
"id": "15",
"parentid": "0",
"text": "Post-Sales Implementation Check List",
"index": "7"
}, {
"id": "16",
"parentid": "15",
"text": "Porting and New Number Details",
"index": "0"
}, {
"id": "18",
"parentid": "15",
"text": "Partner Setup",
"index": "1"
}, {
"id": "19",
"parentid": "15",
"text": "test",
"index": "2"
}, {
"id": "20",
"parentid": "0",
"text": "test",
"index": "11"
}, {
"id": "21",
"parentid": "15",
"text": "test",
"index": "3"
}, {
"id": "23",
"parentid": "5",
"text": "New Polycom",
"index": "0"
}, {
"id": "24",
"parentid": "0",
"text": "Test Markup",
"index": "14"
}, {
"id": "25",
"parentid": "0",
"text": "test",
"index": "15"
}]
After it is formated:
{
"children": [{
"id": "5",
"parentid": "0",
"text": "Device Guides",
"index": "1",
"children": [{
"id": "10",
"index": "0",
"text": "Grandstream GXP-21XX"
}, {
"id": "11",
"index": "1",
"text": "Polycom Soundstation/Soundpoint"
}, {
"id": "23",
"index": "2",
"text": "New Polycom"
}]
}, {
"id": "6",
"parentid": "0",
"text": "Pre-Sales Evaluation",
"index": "0",
"children": []
}, {
"id": "7",
"parentid": "0",
"text": "Router Setup Guides",
"index": "2",
"children": [{
"id": "9",
"index": "0",
"text": "Sonicwall"
}, {
"id": "12",
"index": "1",
"text": "Cisco"
}]
}, {
"id": "9",
"parentid": "7",
"text": "Sonicwall",
"index": "0",
"children": []
}, {
"id": "10",
"parentid": "5",
"text": "Grandstream GXP-21XX",
"index": "0",
"children": []
}, {
"id": "11",
"parentid": "5",
"text": "Polycom Soundstation/Soundpoint",
"index": "1",
"children": []
}, {
"id": "12",
"parentid": "7",
"text": "Cisco",
"index": "1",
"children": []
}, {
"id": "15",
"parentid": "0",
"text": "Post-Sales Implementation Check List",
"index": "7",
"children": [{
"id": "16",
"index": "0",
"text": "Porting and New Number Details"
}, {
"id": "18",
"index": "1",
"text": "Partner Setup"
}, {
"id": "19",
"index": "2",
"text": "test"
}, {
"id": "21",
"index": "3",
"text": "test"
}]
}, {
"id": "16",
"parentid": "15",
"text": "Porting and New Number Details",
"index": "0",
"children": []
}, {
"id": "18",
"parentid": "15",
"text": "Partner Setup",
"index": "1",
"children": []
}, {
"id": "19",
"parentid": "15",
"text": "test",
"index": "2",
"children": []
}, {
"id": "20",
"parentid": "0",
"text": "test",
"index": "11",
"children": []
}, {
"id": "21",
"parentid": "15",
"text": "test",
"index": "3",
"children": []
}, {
"id": "23",
"parentid": "5",
"text": "New Polycom",
"index": "2",
"children": []
}, {
"id": "24",
"parentid": "0",
"text": "Test Markup",
"index": "14",
"children": []
}, {
"id": "25",
"parentid": "0",
"text": "test",
"index": "15",
"children": []
}]
}
Here you go
tree = {0: {children: []}}
data.forEach(function(x) {
x.children = tree[x.id] ? tree[x.id].children : [];
tree[x.id] = x;
if(!tree[x.parentid])
tree[x.parentid] = {children: []}
tree[x.parentid].children.push(x)
})
result = tree[0].children
This solution is linear (iterates over the array just once) and doesn't require any pre-sorting.
http://jsfiddle.net/U47WY/
and here's how to convert the tree back to the linear array:
function flatten(source) {
return source.reduce(function(a, x) {
var children = x.children;
delete x.children;
return a.concat([x], flatten(x.children))
}, []);
}
Following on from a friendly discussion in the comments :
var zeroObj = {"children":[]};
for (var i = 0; i < myArr.length; i++) {
if(myArr[i].parentid === 0) {
zeroObj.children.push(myArr[i]);
} else {
for (var q = 0; q < myArr.length; q++) {
if (myArr[i].parentid == myArr[q].id) {
myArr[q].children = myArr[q].children || [];
myArr[q].children.push(myArr[i]);
};
};
}
};
I have to convert JSON to the format below, I'm having a problem converting it back.
Here is the current format
[{
"id": "5",
"parentid": "0",
"text": "Device Guides",
"index": 0,
"children": [{
"id": "10",
"text": "Grandstream GXP-21XX",
"index": 0
}, {
"id": "11",
"text": "Polycom Soundstation/Soundpoint",
"index": 1
}, {
"id": "23",
"text": "New Polycom",
"index": 2
}]
}, {
"id": "6",
"parentid": "0",
"text": "Pre-Sales Evaluation",
"index": 1,
"children": []
}, {
"id": "7",
"parentid": "0",
"text": "Router Setup Guides",
"index": 2,
"children": [{
"id": "9",
"text": "Sonicwall",
"index": 0
}, {
"id": "12",
"text": "Cisco",
"index": 1
}]
}, {
"id": "9",
"parentid": "7",
"text": "Sonicwall",
"index": 3,
"children": []
}, {
"id": "10",
"parentid": "5",
"text": "Grandstream GXP-21XX",
"index": 4,
"children": []
}, {
"id": "11",
"parentid": "5",
"text": "Polycom Soundstation/Soundpoint",
"index": 5,
"children": []
}, {
"id": "12",
"parentid": "7",
"text": "Cisco",
"index": 6,
"children": []
}]
Here is the format I need it in:
[{
"id": "5",
"parentid": "0",
"text": "Device Guides",
"index": "0"
}, {
"id": "6",
"parentid": "0",
"text": "Pre-Sales Evaluation",
"index": "0"
}, {
"id": "7",
"parentid": "0",
"text": "Router Setup Guides",
"index": "0"
}, {
"id": "9",
"parentid": "7",
"text": "Sonicwall",
"index": "0"
}, {
"id": "10",
"parentid": "5",
"text": "Grandstream GXP-21XX",
"index": "0"
}, {
"id": "11",
"parentid": "5",
"text": "Polycom Soundstation\/Soundpoint",
"index": "0"
}, {
"id": "12",
"parentid": "7",
"text": "Cisco",
"index": "0"
}]
Basically, I have to nest it for the script I'm using but the server is expecting to see it flattened, in the current format the 3rd object dimension starts with "children". I need to unnest children and keep the objects going like the format I need it in.
A first solution, granted you don't want the resulting array to be sorted based on the id:
function visitor(graph) {
var i, l,
nodes=[],
visited=[];
function clone(n) {
// improve the function yourself I'm lazy
var i,l,
props=["id","parentid","index","text"],
result={};
for (i = 0, l = props.length; i < l; i++) {
if (n[props[i]]) {
result[props[i]]= n[props[i]];
}
}
return result;
}
function helper (node) {
var i, limit;
if (visited.indexOf(node.id) == -1) {
visited.push(node.id);
nodes.push(clone(node));
if( node.children) {
for (i = 0, limit = node.children.length; i < limit; i++) {
helper(node.children[i]);
}
}
}
}
for (i = 0, l = graph.length; i < l; i++) {
helper(graph[i]);
}
return nodes;
}
var graph = [{
"id": "5",
"parentid": "0",
"text": "Device Guides",
"index": 0,
"children": [{
"id": "10",
"text": "Grandstream GXP-21XX",
"index": 0
}, {
"id": "11",
"text": "Polycom Soundstation/Soundpoint",
"index": 1
}, {
"id": "23",
"text": "New Polycom",
"index": 2
}]
}, {
"id": "6",
"parentid": "0",
"text": "Pre-Sales Evaluation",
"index": 1,
"children": []
}, {
"id": "7",
"parentid": "0",
"text": "Router Setup Guides",
"index": 2,
"children": [{
"id": "9",
"text": "Sonicwall",
"index": 0
}, {
"id": "12",
"text": "Cisco",
"index": 1
}]
}, {
"id": "9",
"parentid": "7",
"text": "Sonicwall",
"index": 3,
"children": []
}, {
"id": "10",
"parentid": "5",
"text": "Grandstream GXP-21XX",
"index": 4,
"children": []
}, {
"id": "11",
"parentid": "5",
"text": "Polycom Soundstation/Soundpoint",
"index": 5,
"children": []
}, {
"id": "12",
"parentid": "7",
"text": "Cisco",
"index": 6,
"children": []
}];
nodes = visitor(graph);
And yes, I know, the helper function relay on side effects but I've scoped them into the visitor function to reduce harm and there is room for improvements (at least sorting the resulting array based on the id) but I will leave them to you