How to output an array to a table?

I need to output an array to a table with images for each item and add a class if items belong to friends. I know how to get it as single string, but I’ve no idea how to display it as a table.
Here is the array:

const data = {
    "rating": [
        {
            "id": "123",
            "name": "Владимир",
            "lastName": "Ларионов",
            "img": "./male.png",
            "points": "463"
        },
        {
            "id": "9",
            "name": "Владимир",
            "lastName": "Сергеев",
            "img": "./male.png",
            "points": "521"
        },
        {
            "id": "231",
            "name": "Вениамин",
            "lastName": "Васильев",
            "img": "./male.png",
            "points": "865"
        }
    ],
    "friends": [
        {
            "id": "9",
            "name": "Владимир",
            "lastName": "Сергеев",
            "img": "./male.png"
        },
        {
            "id": "4",
            "name": "Эрик",
            "lastName": "Аксёнов",
            "img": "./male.png"
        }
    ]
}

14 thoughts on “How to output an array to a table?”

  1. something like that ?

    const data = 
          { rating: 
            [ { id: '123', name: 'Владимир', lastName: 'Ларионов', img: './male.png', points: '463' }
            , { id:   '9', name: 'Владимир', lastName: 'Сергеев',  img: './male.png', points: '521' } 
            , { id: '231', name: 'Вениамин', lastName: 'Васильев', img: './male.png', points: '865' } 
            ] 
          , friends: 
            [ { id: '9', name: 'Владимир', lastName: 'Сергеев', img: './male.png' } 
            , { id: '4', name: 'Эрик',     lastName: 'Аксёнов', img: './male.png' } 
            ] 
          } 
    
    function createTable( caption, arrObj)
      {
      let newTable  = document.body.appendChild(document.createElement('table'))
        , colNames  = Object.keys(arrObj[0])
        , tableHead = newTable.createTHead()
        , tableBody = newTable.createTBody()
        ;
      newTable.createCaption().textContent = caption
    
      let H_Row = tableHead.insertRow()
      colNames.forEach(cName => H_Row.insertCell().textContent = cName )
    
      arrObj.forEach(lineObj =>
        {
        let newRow = tableBody.insertRow()
        colNames.forEach(cName =>
          {
          if ( cName != 'img')
            newRow.insertCell().textContent = lineObj[cName]
          else
            newRow.insertCell().innerHTML = `<img src="${lineObj[cName]}">`
          })
        })
      }
    
    for (let name in data) createTable( name, data[name] )
    table  {
      border-collapse : collapse;
      margin          : 2em 1em;
      }
    table td {
      padding    : .2em .8em;
      border     : 1px solid darkblue;
      }
    table thead {
      background-color: aquamarine;
      }
    Reply

Leave a Comment