123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- const renderTableFromJSON = (parent, jsonObj) => {
- const buildButton = (value, parent) => {
- const button = document.createElement('button');
- button.type = 'button';
- button.textContent = value;
- button.addEventListener('click', () => {
- button.remove();
- renderTableFromJSON(parent, `${value}`)
- });
- return parent.appendChild(button);
- }
- const insertButton = (value, parent) => {
- if(typeof value === 'string' && value.includes('https://swapi.dev/api/')) {
- return buildButton(value, parent);
- } else if(typeof value === 'object') {
- value.forEach((element, index) => {
- if(element.includes('https://swapi.dev/api/')) {
- value[index] = buildButton(element, parent);
- }
- });
- return value;
- } else {
- return parent.append(value);
- }
- }
- const tableConstruct = json => {
- let tableElement = document.createElement('table');
- for (const row in json) {
- const tableRowElement = document.createElement('tr');
- tableRowElement.insertCell(0).innerHTML = `${row}`;
- insertButton(json[row], tableRowElement.insertCell(1));
- tableElement.appendChild(tableRowElement);
- }
- return tableElement;
- }
- fetch(`${jsonObj}`)
- .then(response => response.json())
- .then(luke => {
- parent.appendChild(tableConstruct(luke));
- });
- }
- renderTableFromJSON(document.body, 'https://swapi.dev/api/people/1/');
|