main.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. fetch('https://swapi.dev/api/people/1/')
  2. .then(res => res.json())
  3. .then(data => renderTree(root, data))
  4. const renderTree = (el, json) => {
  5. let table = document.createElement('table')
  6. table.setAttribute('border', '1px')
  7. for (const [key, value] of Object.entries(json)) {
  8. let tr = document.createElement('tr')
  9. let th = document.createElement('th')
  10. let td = document.createElement('td')
  11. let button = document.createElement('button')
  12. th.innerText = key
  13. if (typeof (value) === 'object') {
  14. let deepTable = document.createElement('table')
  15. deepTable.setAttribute('border', '1px')
  16. deepTable.style.width = '100%'
  17. value.map(t => {
  18. let deepTr = document.createElement('tr')
  19. let deepTd = document.createElement('td')
  20. let deepButton = document.createElement('button')
  21. deepButton.innerText = t.slice(22, -1)
  22. deepButton.onclick = () => reRenderTree(deepTd, t)
  23. deepTd.append(deepButton)
  24. deepTr.append(deepTd)
  25. deepTable.append(deepTr)
  26. })
  27. td.append(deepTable)
  28. } else if (typeof value === 'string' && !value.indexOf('https://')) {
  29. button.innerText = value.slice(22,-1)
  30. button.onclick = () => reRenderTree(td, value)
  31. td.append(button)
  32. } else {
  33. /\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])*/.test(value) ? td.innerText = value.slice(0, 10) : td.innerText = value
  34. }
  35. tr.append(th)
  36. tr.append(td)
  37. table.append(tr)
  38. }
  39. el.append(table)
  40. }
  41. const reRenderTree = (el, link) => {
  42. el.removeChild(el.firstChild)
  43. return fetch(link)
  44. .then(res => res.json())
  45. .then(data => renderTree(el, data))
  46. }