I am a beginner in javascript object and tree creation, so please bear with me. I have an array of objects like this
[
{
"l1": 1,
"l2": 2,
"l3": 3,
"l4": 4,
"l5": 5,
"l6": null
},
{
"l1": 1,
"l2": 2,
"l3": 3,
"l4": 4,
"l5": 6,
"l6": null
},
{
"l1": 1,
"l2": 2,
"l3": 7,
"l4": 8,
"l5": 9,
"l6": null
},
{
"l1": 1,
"l2": 2,
"l3": 7,
"l4": 8,
"l5": 10,
"l6": null
},
{
"l1": 1,
"l2": 2,
"l3": 3,
"l4": 11,
"l5": 12,
"l6": null
},
{
"l1": 1,
"l2": 2,
"l3": 3,
"l4": 11,
"l5": 13,
"l6": null
}
]
I have stored this data in json file, and I want to create a tree-structure-like object using this array of objects. Something like this.
{
"1": [
{
"2": [
{
"3": [
{
"4": [
{
"5": [
null
]
},
{
"6": [
null
]
}
]
},
{
"11": [
{
"12": [
null
]
},
{
"13": [
null
]
}
]
}
]
},
{
"7": [
{
"8": [
{
"9": [
null
]
},
{
"10": [
null
]
}
]
}
]
}
]
}
]
}
I am trying to do this on my own but I'm failing right in the beginning itself.
This is my attempt
var fs = require('fs');
var file = 'levels.json';
var content = fs.readFileSync(file, { encoding: 'binary' });
var obj = {}
JSON.parse(content).forEach((curr, i, arr)=>{
if(curr.l1){
obj[curr.l1] = []
}
if(curr.l2){
var l2obj = {}
l2obj[curr.l2] = []
obj[curr.l1].push(l2obj)
// obj[curr.l1].push({curr.l2:[]})
}
})
fs.writeFileSync('theObject.json', JSON.stringify(obj), 'utf8');
The problem I found out is that the line l2obj[curr.l2] = []
is overwriting the previous array and I'm not able to nest them properly.SAme problem exists with the line obj[curr.l1] = []
. I tried the commented line as well but it throwing syntax error. I feel it is pretty basic but also very confusing, how do I create objects from dynamic values and push them to an array without overwriting the previous one. Any suggestions, hints.
Second line of question, Is this the best way to represent data like this? I wanted to use a tree structure because it seemed like an accurate and shortest form of data structure.The json data has almost 20k objects with level information. Suggestions are highly appreciated.