I have an array in JSON, I need to pass it in JS
that its printing will be like the image in HTML
After trying to print to console.log
– it really prints in order
It’s just that during the creation of the HTML elements everything was a mess
This is my array:
JavaScript
x
43
43
1
[
2
{
3
"id": "1",
4
"name": "sara",
5
"children": [
6
{
7
"id": "2",
8
"name": "dian"
9
},
10
{
11
"id": "3",
12
"name": "michael",
13
"children": [
14
{
15
"id": "4",
16
"name": "dkny"
17
},
18
{
19
"id": "5",
20
"name": "Anne"
21
}
22
]
23
}
24
25
]
26
},
27
{
28
"id": "6",
29
"name": "Tommy"
30
},
31
{
32
"id": "7",
33
"name": "danken",
34
"children": [
35
{
36
"id": "8",
37
"name": "biria"
38
}
39
]
40
}
41
42
]
43
And I want it to be printed as in the picture,
Each square is a DIV I would love to get help from infected people like you, I’m desperate already
Advertisement
Answer
You can programmatically render each object and recursively render each of its children :
JavaScript
1
47
47
1
const root = JSON.parse('[{ "id": "1", "name": "sara", "children": [ { "id": "2", "name": "dian" }, { "id": "3", "name": "michael", "children": [ { "id": "4", "name": "dkny" }, { "id": "5", "name": "Anne" } ] } ] }, { "id": "6", "name": "Tommy" }, { "id": "7", "name": "danken", "children": [ { "id": "8", "name": "biria" } ] } ]')
2
3
const container = document.createElement('div')
4
container.style.display = 'flex'
5
container.style.gap = '1em'
6
7
const render = obj => {
8
const div = document.createElement('div')
9
const nameSpan = document.createElement('span')
10
const idSpan = document.createElement('span')
11
12
nameSpan.textContent = `name: ${ obj.name }`
13
idSpan.textContent = `id: ${ obj.id }`
14
15
div.appendChild(nameSpan)
16
div.appendChild(idSpan)
17
18
div.style.display = 'flex'
19
div.style.flexDirection = 'column'
20
div.style.border = '5px solid black'
21
div.style.borderRadius = '5px'
22
div.style.padding = '5px'
23
24
if (obj.children) {
25
const childrenContainer = document.createElement('div')
26
const childrenContainerSpan = document.createElement('span')
27
28
childrenContainerSpan.textContent = 'children: '
29
childrenContainer.appendChild(childrenContainerSpan)
30
31
childrenContainer.style.display = 'flex'
32
childrenContainer.style.gap = '1em'
33
34
obj.children.forEach(e => childrenContainer.appendChild(render(e)))
35
36
div.appendChild(childrenContainer)
37
}
38
39
return div
40
}
41
42
root.forEach(e => container.appendChild(render(e)))
43
44
45
window.onload = () => {
46
document.body.appendChild(container)
47
}