Hello, could someone please assess this?
Link to task: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Test_your_skills:_JSON
Link to my code: https://jsfiddle.net/Keyboardguy/p0hu7gjw/8/
Thanks, Keyboardguy
Hello, could someone please assess this?
Link to task: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Test_your_skills:_JSON
Link to my code: https://jsfiddle.net/Keyboardguy/p0hu7gjw/8/
Thanks, Keyboardguy
Hi @Keyboardguy
Well solved. Congrats!
Two improvements:
for
loop or a forEach
loop where the index is already integrated.Keep up the great work,
Michael
Hello,
Thank you for the feedback! I used a for ... of
loop just because it looked nicer. Also, counting only one gender and calculating from the total is definitely much more efficient than my code counting both.
Thanks, Keyboardguy
this is my code, any suggestions for improvement:
const section = document.querySelector(βsectionβ);
let para1 = document.createElement(βpβ);
let para2 = document.createElement(βpβ);
let motherInfo = 'The mother cats are called ';
let kittenInfo;
async function populate() {
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(obj) {
const objJson = JSON.parse(obj);
let total = 0;
let male = 0;
let female = 0;
motherInfo = motherInfo + objJson.map(catName => catName.name).join(",");
for (cat of objJson) {
total += cat.kittens.length;
for (kitten of cat.kittens) {
if (kitten.gender === "m") {
male += 1;
} else {
female += 1;
}
}
}
kittenInfo = `Total is ${total} no. of male is ${male} no of female ${female}`
para1.textContent = motherInfo;
para2.textContent = kittenInfo;
}
populate();
section.appendChild(para1);
section.appendChild(para2);
Hi @issadaas and welcome to the community
Well done! I have only two small improvements:
${total - male}
for...of
loops we should always use const
(or let
) for the variable: for (const cat of objJson) {
I hope that helps.
By the way, if you plan on doing more tasks it would be helpful if you could share your code in an online editor like https://codepen.io/, https://glitch.com or https://jsfiddle.net/ and create a new topic. Thank you
Cheers,
Michael