|
@@ -0,0 +1,51 @@
|
|
|
+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/');
|