I am trying to reformat some relatively unstructured json to fit my needs, where I want each object to have a ‘name’ attribute as well as a ‘children’ array for sub-objects. I have a json file that looks like below:
JavaScript
x
10
10
1
{
2
"varA":true,
3
"varB":false,
4
"varC": {
5
"time":"15:00:00",
6
"date":"Jul 10",
7
"items":["apple", banana"]
8
}
9
}
10
I would like to format it to be something like this:
JavaScript
1
43
43
1
{
2
"name": "data",
3
"children": [
4
{
5
"name": "varA",
6
"children": [
7
{"name": "true"}
8
]
9
},
10
{
11
"name": "varB",
12
"children": [
13
{"name": "false"}
14
]
15
},
16
{
17
"name": "varC",
18
"children": [
19
{
20
"name": "time",
21
"children": [
22
{"name": "15:00:00"}
23
]
24
},
25
{
26
"name": "date",
27
"children": [
28
{"name": "Jul 10"}
29
]
30
},
31
{
32
"name": "items",
33
"children": [
34
{"name": "apple"},
35
{"name": "banana"}
36
]
37
}
38
]
39
}
40
41
]
42
}
43
How would I be able to do this recursively using pure js, in the case that objects can have a different depths of subobjects? Or is it still possible to do it iteratively?
Thanks in advance!!!
Advertisement
Answer
JavaScript
1
32
32
1
const data = {
2
"varA":true,
3
"varB":false,
4
"varC": {
5
"time":"15:00:00",
6
"date":"Jul 10",
7
"items":["apple", "banana"]
8
}
9
}
10
11
function parse(key, val) {
12
if (val === undefined) return { name: key };
13
14
15
if (typeof val !== "object") {
16
return {
17
name: key,
18
children: [
19
parse(val)
20
]
21
}
22
}
23
24
25
return {
26
name: key,
27
children: Object.entries(val).map(([newKey, newVal]) => parse(newKey, newVal))
28
}
29
}
30
31
const parsedData = parse("data", data)
32