I have the following 2D array cells
:
ID Name Parent
1 Bob 0
2 Alice 1
3 John 2
4 Jane 2
5 Jenny 3
6 Jonny 2
I want to convert it into nested JSON format, such that each object has the following attributes:
name
Array of children, which includes also objects with names and arrays of children. There are no circular nestings in the array; a child can't have any of its parents as children.
Here is the function I wrote:
function getChildren(node){
console.log('Getting Children for' + node)
children = []
for(i = 0;i < cells.length; i++){
if(cells[i][2] == node){
cell = cells[i]
child = {}
child.name = cell[1]
child.children = getChildren(cell[0])
children.push(child)
}
}
return children
}
text = "ID Name Parent\n1 Bob 0\n2 Alice 1\n3 John 2\n4 Jane 2\n5 Jenny 3\n6 Jonny 2\n"
lines = text.split('\n')
cells = []
for(i = 0; i < lines.length; i++){
cells[i] = lines[i].split(/\ +/)
}
Calling the function on node 6 getChildren(6)
, gives this output:
Getting Children for6
[]
Which is correct because node 6 has no children.
But calling the function on nodes with children, for example getChildren(3)
, gives:
Getting Children for3
Getting Children for5Object children: Array[1] 0: Object children: Array[1] 0: Object children: Array[1] name: "Jenny" length: 1 name: "Jenny" length: 1 name: "Jenny"
From the console output it seems like it calls the right functions, but why is the object for "jenny" infinitely nested under all children?
I want to end up with a JSON object that I could use JSON.stringify
on. Calling the function on getChildren(3)
gives the error
Uncaught TypeError: Converting circular structure to JSON.
I think this is because the object for Jenny is infinitely nested under each child.