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>";
});
This is from challenge
https://learn.freecodecamp.org/data-visualization/json-apis-and-ajax/convert-json-data-to-html
The part that’s confusing is the
var keys = Object.keys(val)
So val would be each element in the json object.
Does Object refer to the object called json in this case?
Object
is a javascript object constructor (native) which has a method keys()
built into, just like arrays have map, filter, reduce
etc. It accepts an object and returns all of the keys in an array.
For example:
Object.keys({
cat: 'meow',
dog: 'woof',
duck: 'quack'
});
This would return
['cat', 'dog', 'duck'];
You can read more here on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
In your example, json
would be an array of objects, which returns each object as val
(in your example) then you store all the keys of that object a variable keys
as an array, using Object.keys()
method.
1 Like
forEach works with arrays.
["apple", "banana", "cherry"].forEach(val){
console.log(val);
});
// apple
// banana
// cherry
so the val
part of a forEach
would be each element one at a time.
Object.keys
works with objects.
Object.keys({"first": "kerafyrm", "last": "02"});
// [“first”, “last”]
this returns an array of all the keys.
So in the example you have,. I’m assuming json
is an array of objects.
To further complicate this,. each object could have an array.
As you know [] is array.
As you know {} is an object.
let json = [{"names": ["red", "blue"]}, {"sizes": ["large", "small"]}];
could be an example.
each object is the val.
[“names”, “sizes”] are the Object.keys
[“red”, “blue”] & [“large”, “small”] would be the forEach key
1 Like
Thank you both. Is there a lesson on FCC that teaches this beforehand? Seems thrown in at a bad time since understanding the main gist of the challenge involves pre-requisite knowledge