I would like to 'translate' a list of objects into a json format edible by jstree:
data = [
{
"data" : {
"title" : "father",
"attr" : { "href" : "#" }
},
"children" : [
{
"data" : {
"title" : "Older Son",
"attr" : { "href" : "#" }
},
"children" : []
},
{
"data" : {
"title" : "Younger Son",
"attr" : { "href" : "#" }
},
"children" : []
}
]
},
]
My input looks like this:
[
Object
id: 35
name: "bnm,bnm"
parent_id: null
,
Object
id: 36
name: "ghk"
parent_id: 35
,
Object
id: 37
name: "hgkgh"
parent_id: null
,
Object
id: 38
name: "jklhjk"
parent_id: null
,
Object
id: 39
name: "fghdfgh"
parent_id: 38
,
Object
id: 40
name: "bsdbd"
parent_id: 38
,
...]
Well, to be honest, this would not be a tree, rather a forest. But it doesn't matter.
I've spent quite a lot of time on it, but failed to get it working. Operating on arrays seems to be nasty in javascript (in comparison to Java,C++ or PHP)...
What I've tried so far is:
- (pre) the source data (list of objects) meet one condition: a son can't be present before it's parent
- make it associative array (key=id, value=object), so it had to be string-keyed.
- pop last array element and push it inside its parent element's children array. Repeat this for all non-null-parent elements.
- hoped this should work.