I went through the challenge by copying the code from the wording, however I really do not understand how it works:
json.forEach(function(val) {
var keys = Object.keys(val);
html += "<div class = 'cat'>";
keys.forEach(function(key) {
html += "<strong>" + key + "</strong>: " + val[key] + "<br>";
});
html += "</div><br>";
});
Can someone explain me what are exactly val and key(s) and what they are used for in this code? This is quite confusing to me.
I’ve changed the code to be more readable
objects.forEach(function(object) {
var keys = Object.keys(object);
html += "<div class = 'cat'>";
keys.forEach(function(key) {
var value = object[key];
html += "<strong>" + key + "</strong>: " + value + "<br>";
});
html += "</div><br>";
});
So:
variable objects
stores an array of objects: [object1, object2, object3]
object
consists of [key]: [value]
pairs
Example of an object:
{
id: 0,
imageLink: "https://s3.amazonaws.com/freecodecamp/funny-cat.jpg",
altText: "A white cat wearing a green helmet shaped melon on it's head. "
}
To access object’s value we use this notation: object[key]
ie. value of id
key of above object is 0; to access this value, we write: object[id]
a functional equivalent of the code:
$("#getMessage").on("click", function() {
$.getJSON("/json/cats.json", function(objects) {
var html = objects
.map(objectToHtmlString)
.join('\n')
$(".message").html(html);
})
})
});
// takes object and returns
// array of key value pairs
//
// example:
// {id: 0, name: 'tom'} is converted to:
// [
// {key: 'id', value: 0},
// {key: 'name', value: 'tom'}
// ]
var toPairs = (object) => Object.keys(object)
.map( (key) => ({key, value: object[key]}) )
// converts object to its html representation
var objectToHtmlString = (object) =>
'<div class="cat">' +
toPairs(object)
.map(pairToHtml)
.join('\n') +
'</div><br />'
// takes pair and returns corresponding html
//
// example:
// {key: 'id', value: 0} is converted to:
// <strong>id</strong>: 0<br />
var pairToHtml = ({key, value}) => `<strong>${key}</strong>: ${value}<br />`
It makes a lot more sense now, thank you!