ejemplo 2

Ejemplo de aplicación parcial

by Juan Manuel Cruz

CSS

table,
thead,
tbody,
tr {
  width: 100%;
}

tr {
  display: flex;
  width: 100%;
  justify-items: space-around;
}

td,
th {
  padding: 1rem;
  flex-grow: 1;
  text-align: center;
}

JavaScript

(function() {
  let usuarios = [{
    id: 5,
    nombre: 'Usuario 1',
    correo: '[email protected]'
  }, {
    id: 2,
    nombre: 'Usuario 2',
    correo: '[email protected]'
  }, {
    id: 11,
    nombre: 'Usuario 3',
    correo: '[email protected]'
  }, {
    id: 3,
    nombre: 'Usuario 5',
    correo: '[email protected]'
  }, {
    id: 13,
    nombre: 'Usuario 8',
    correo: '[email protected]'
  }, {
    id: 7,
    nombre: 'Usuario 1',
    correo: '[email protected]'
  }, ]

  const cabeceras = ['ID', 'Nombre', 'E-Mail']

  const popular = elemento => objetos => {
  	if (!Array.isArray(objetos)) objetos = [objetos]
    objetos.reduce((node, child) => {
      node.insertAdjacentElement('beforeend', child)
      return node
    }, elemento)
    return elemento
  }
  
  const inRowElement = tipo => innerText => {
  	const elem = document.createElement(tipo)
    elem.innerHTML = innerText || ''
    return elem
  }

	const strToTD = inRowElement('td')
	const strToTH = inRowElement('th')
  
  const objToTR = (objeto, orden = ['id', 'nombre', 'correo']) => {
    return popular
    	(document.createElement('tr'))
      (orden.map(x => strToTD(objeto[x])))
  }

  const pruneElement = node => {
    if (!node.firstChild) return node
    node.innerHTML = ''
    if (node.firstChild)
      node.removeChild(node.firstChild)
    return pruneElement(node)
  }


  const renderTabla = (datos = usuarios) => {
    const body = document.getElementsByTagName('body')[0]
    pruneElement(body)
    const table = document.createElement('table')
    const thead = document.createElement('thead')
    const tbody = document.createElement('tbody')
    
    const popularTHEAD = popular(thead)
    const popularTBODY = popular(tbody)
    
    popularTHEAD(
    	popular
    		(document.createElement('tr'))
    		(cabeceras.map(x => strToTH(x)))
    )
   
    popularTBODY(
    	datos.map(x => objToTR(x))
    )

    table.appendChild(thead)
    table.appendChild(tbody)
   ...