Though not common, but sometimes you might find yourself in situations where you need to loop through a Javascript object. Unlike strings and arrays, objects, literal objects with curly brackets and key: value pair are not considered to be iterable.
So, if you go with the for... of
method to iterate the following objects like so:
const fruitsQty = {
melon: 10,
apple: 15,
grape: 7,
pineapple: 10,
jackfruit: 22,
strawberry: 14,
orange: 30}
for (let exm of fruitsQty) {
console.log(exm)
}
You'll get an error.
However, if you present that object key:value pairs as an array, you'll be able to use the for...of
method.
In order to do that, you need to use special methods: Object.keys()
to return an actual array containing the keys out of the object as an array, Object.values()
to return an actual array made up of the values out of that object and Object.entries()
which will return a literal nested arrays of the key:value pair of that object.
Object.keys(fruitsQty) // (7) ["melon", "apple", "grape", "pineapple", "jackfruit", "strawberry", "orange"]
Object.values(fruitsQty) // (7) [10, 15, 7, 10, 22, 14, 30]
Object.entries(fruitsQty) // ["melon" 10, "apple" 15, "grape" 7, "pineapple" 10, "jackfruit" 22, "strawberry" 14, "orange" 30
Now that we have those presented as an array (technically they are not turned into an array, we just sort of make array out of an object, ok apologies if this is confusing lol), we can use the previous for...of
method to iterate that object because that does work with an array.
Here's an example of iterating over the quantity of the fruit
for (let quantity of Object.values(fruitsQty) {
console.log(quantity)
}
//
10
15
7
10
22
14
30
Basically, using those three methods will allow you iterate over objects using the for..of
method as if they are an array. You can also loop through them to get the total quantity of the fruits.
let sum = 0;
for (let quantity of Object.values(fruitsQty) {
sum += quantity;
}
// Each time it loops, the sum adds each fruit quantity
// 108
Since those keys and values are behaving like an array with those methods, you can also find out the length of the fruits quantity, like so:
// first, create a variable that stores the fruit quantity information as an array
let quantity = Object.values(fruitsQty);
console.log(quantity.length) // 7