Loop inside objects
Hasan TEZCAN
Posted on March 15, 2022
We can travel inside Arrays with map, forEach and reduce function. What if we want to travel inside objects. As you known as objects has key and value so we can use those one all in one or separately.
Object.keys, values, entries
For plain objects, the following methods are available:
Object.keys(obj) – returns an array of keys.
Object.values(obj) – returns an array of values.
Object.entries(obj) – returns an array of [key, value] pairs.
let prices = {
banana: 1,
orange: 2,
meat: 4,
};
let doublePrices = Object.fromEntries(
// convert prices to array, map each key/value pair into another pair
// and then fromEntries gives back the object
Object.entries(prices).map(entry => [entry[0], entry[1] * 2])
);
alert(doublePrices.meat); // 8
Training question: Kata 8kyu Pirates!! Are the Cannons ready!
Source
💖 💪 🙅 🚩
Hasan TEZCAN
Posted on March 15, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.