Зміст курсу
JavaScript Data Structures
JavaScript Data Structures
Object Iteration with for...in Loop
In this section, we will explore advanced concepts of working with objects. Specifically, we will cover iteration through objects and helpful methods JavaScript offers to work with objects effectively. Let's get started.
for...in loop
To work with the properties of an object, including iterating through them, we can use the for...in
loop. This loop allows us to traverse an object and access its properties and their values.
The for...in
loop is a construct in JavaScript designed specifically for iterating over the properties of an object. It provides a way to access each property's name (key) and its corresponding value.
Here's the basic syntax of the for...in
loop:
key
: A variable that will hold the name of the current property during each iteration;object
: The object we want to iterate through.
Iterating Through Object Properties in Practice
Let's consider an example with an object representing a flower:
Now, let's use the for...in
loop to iterate through the properties of the flower
object and log each property name and its value:
const flower = { genus: "Allium", species: "Allium sativum", color: "Purple", height: 24, isEdible: true, isBlooming: true, }; for (let key in flower) { console.log(`Property: ${key}, Value: ${flower[key]}`); }
Дякуємо за ваш відгук!