fetchImproved.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. const renderTableFromJSON = (parent, jsonObj) => {
  2. const buildButton = (value, parent) => {
  3. const button = document.createElement('button');
  4. button.type = 'button';
  5. button.textContent = value;
  6. button.addEventListener('click', () => {
  7. button.remove();
  8. renderTableFromJSON(parent, `${value}`)
  9. });
  10. return parent.appendChild(button);
  11. }
  12. const insertButton = (value, parent) => {
  13. if(typeof value === 'string' && value.includes('https://swapi.dev/api/')) {
  14. return buildButton(value, parent);
  15. } else if(typeof value === 'object') {
  16. value.forEach((element, index) => {
  17. if(element.includes('https://swapi.dev/api/')) {
  18. value[index] = buildButton(element, parent);
  19. }
  20. });
  21. return value;
  22. } else {
  23. return parent.append(value);
  24. }
  25. }
  26. const tableConstruct = json => {
  27. let tableElement = document.createElement('table');
  28. for (const row in json) {
  29. const tableRowElement = document.createElement('tr');
  30. tableRowElement.insertCell(0).innerHTML = `${row}`;
  31. insertButton(json[row], tableRowElement.insertCell(1));
  32. tableElement.appendChild(tableRowElement);
  33. }
  34. return tableElement;
  35. }
  36. fetch(`${jsonObj}`)
  37. .then(response => response.json())
  38. .then(luke => {
  39. parent.appendChild(tableConstruct(luke));
  40. });
  41. }
  42. renderTableFromJSON(document.body, 'https://swapi.dev/api/people/1/');