Iterate Over an Object
To iterate over all properties in an object, we can use the loop for...in...
to iterate over the keys:
The syntax:
for (let key in object) {
// do something for each key in the object
}
Example:
let fruits = {'apple':'red', 'pear':'green', 'banana':'yellow', 'plum':'purple'}
for (let k in fruits) {
console.log(k + ' is ' + fruits[k])
}
Console result:
apple is red
pear is green
banana is yellow
plum is purple
Here in the for
loop, variable k
receives the keys of object fruits
('apple', 'pear'
...). Then fruits[k]
is used to access the value paired with the key k
.
Demo Objects in CodeCraft
We can use an object to store column color and height values to build columns.
Example:
let collection = {'box_red': 10, 'box_green': 6, 'box_blue': 8, 'box_pink': 2};
let x = 0;
for (let m in collection) {
console.log(m);
column(x, -20, collection[m], m);
x += 2;
}
See console result:
box_red
box_green
box_blue
box_pink