JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>JSON: Task 1</title>
<link rel="stylesheet" href="styles/style.css">
</head>
<body>
<section class="preview">
</section>
</body>
<script src="scripts/script.js"></script>
</html>
CSS
p {
color: purple;
margin: 0.5em 0;
}
* {
box-sizing: border-box;
}
JavaScript
const section = document.querySelector('section');
let para1 = document.createElement('p');
let para2 = document.createElement('p');
let motherInfo = 'The mother cats are called ';
let kittenInfo;
const requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/tasks/json/sample.json';
fetch(requestURL)
.then(response => response.text())
.then(text => displayCatInfo(text))
function displayCatInfo(catString) {
let total = 0;
let male = 0;
catString = JSON.parse(catString);
for(let x = 0; x < catString.length; x++) {
motherInfo = motherInfo + catString[x].name + ", ";
for(let z = 0; z < catString[x].kittens.length; z++) {
total++;
if(catString[x].kittens[z].gender === "m") {
male++;
}
}
}
kittenInfo = `There are a total of ${total} kittens. There are ${male} male kittens and ${total - male} female kittens.`
motherInfo = motherInfo.slice(0, (motherInfo.length - (catString[catString.length - 1].name.length + 2)));
motherInfo = motherInfo.concat("", `and ${catString[catString.length - 1].name}.`);
para1.textContent = motherInfo;
para2.textContent = kittenInfo;
}
section.appendChild(para1);
section.appendChild(para2);