r/javaScriptStudyGroup • u/IsuckatJS • Nov 06 '17
Help with Star Wars api and js
Hi,
Hope everyone is doing great :)
I am quite rusty with js and wanted to practise by pulling data from the star wars api and dynamically inserting it into divs. Specifically I am pulling planet information, using the key values to populate the " table" header(i am using css display:table). The rows of the table should be each planet + information(limited to 7 items). The script below seems to do this for the first planet but cant for the life of me figure out how to make it go through each planet and do that. Obviously feel free to laugh/mock/kudos/criticize my code, it would help me loads.
Any ideas?
Thanks everyone!
const fetchPlanets = fetch('https://swapi.co/api/planets/');
getPlanets();
function getPlanets(){
fetchPlanets.then(
(data) => data.json()
)
.then(
(planetList)=> {
let planetItems = planetList.results;
console.log(planetItems);
for (var i = 0; i < planetItems.length; i++) {
let planets = document.getElementById("planets");
let tableHeader = document.getElementById("table-header");
let tableRow = document.createElement("div");
planets.setAttribute("class", "table");
tableHeader.setAttribute("class", "table-header");
tableRow.setAttribute("class", "table-row");
let keyTitles = Object.keys(planetItems[0]);
for (var i =0; i < keyTitles.length; i++){
if(i < 7) {
let tableCellHeader = document.createElement("div");
let tableCell = document.createElement("div");
let planetData = Object.values(planetItems[i]);
tableCellHeader.setAttribute("class", "table-cell");
tableCellHeader.innerHTML = keyTitles[i].replace("_", " ");
tableHeader.appendChild(tableCellHeader);
//planetData rows
planets.appendChild(tableRow);
tableRow.appendChild(tableCell);
tableCell.setAttribute("class", "table-cell");
tableCell.innerHTML = planetData[i];
}
}
}
}
)
}