Skip to content
Advertisement

printing arry of object in object in Html from JS and Json

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:

[
  {
    "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"
      }
    ]
  }

]

And I want it to be printed as in the picture, enter image description here

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 :

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" } ] } ]')

const container = document.createElement('div')
container.style.display = 'flex'
container.style.gap = '1em'

const render = obj => {
    const div = document.createElement('div')
    const nameSpan = document.createElement('span')
    const idSpan = document.createElement('span')

    nameSpan.textContent = `name: ${ obj.name }`
    idSpan.textContent   = `id: ${ obj.id }`

    div.appendChild(nameSpan)
    div.appendChild(idSpan)
    
    div.style.display = 'flex'
    div.style.flexDirection = 'column'
    div.style.border = '5px solid black'
    div.style.borderRadius = '5px'
    div.style.padding = '5px'

    if (obj.children) {
        const childrenContainer = document.createElement('div')
        const childrenContainerSpan = document.createElement('span')

        childrenContainerSpan.textContent = 'children: '
        childrenContainer.appendChild(childrenContainerSpan)

        childrenContainer.style.display = 'flex'
        childrenContainer.style.gap = '1em'

        obj.children.forEach(e => childrenContainer.appendChild(render(e)))

        div.appendChild(childrenContainer)
    }

    return div
}

root.forEach(e => container.appendChild(render(e)))


window.onload = () => {
    document.body.appendChild(container)
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement