In this blog post, we will discuss a JavaScript program that allows you to iterate through an object and print its key-value pairs. This program is useful when you need to access and display the properties and values of an object dynamically. Let’s dive into the code and understand how it works.
Code
const user = {
name: "joe",
age: 32,
occupation: "Web Developer"
};
for (const [key, value] of Object.entries(user)) {
console.log(`${key} => ${value}`);
}
Code Explanation
The provided code snippet demonstrates the use of the Object.entries()
method and a for...of
loop to iterate through an object. Here’s how it works:
1. Firstly, we have an object named user
which contains three properties: name
, age
, and occupation
.
2. The Object.entries()
method is used to convert the object into an array of its key-value pairs.
3. The for...of
loop is then used to iterate through each key-value pair within the newly created array.
4. Inside the loop, we use template literals to print each key-value pair to the console.
Let’s run this code and see the output:
const user = {
name: "joe",
age: 32,
occupation: "Web Developer"
};
for (const [key, value] of Object.entries(user)) {
console.log(${key} => ${value}
);
}
Output:
name => joe
age => 32
occupation => Web Developer
`
In the output, you can see that the program successfully prints each key-value pair of the user
object. This method allows you to access and display any object’s properties and values dynamically.
Conclusion
In this blog post, we discussed a JavaScript program that iterates through an object and prints its key-value pairs. This program is an efficient way to access and display object properties dynamically. By using the `Object.entries()` method and a `for…of` loop, we can easily work with objects in JavaScript. Hopefully, this program will be helpful for students and professionals who are learning or working with JavaScript.
Also checkout the following codes.
How to Use JavaScript Objects and Methods: Program to Give Details of an Example
Program to Get the Energy Level of a Robot