Steps to iterate over an object using Javascript
const my_obj = {
"name": "John",
"city": "New York",
"profession": "engineer"
};
Object.keys(my_obj).forEach( key => {
console.log(my_obj[key]);
})
Output
John
New York
engineer
The above code example uses the Object.keys() method to loop through the properties of the my_obj object. For each property, the value of the property is logged to the console.
The Object.keys(my_obj) method returns the following array:
["name","city","profession"]
We can also use Javascript for loop to iterate over this array and get the value from the object in each iteration.
const my_obj = {
"name": "John",
"city": "New York",
"profession": "engineer"
};
const all_keys = Object.keys(my_obj);
for (let i=0; i < all_keys.length; i++) {
console.log( my_obj[all_keys[i]] );
}
Output
John
New York
engineer
The above code example is used to iterate through an object and output the values of each key. The code begins by declaring a constant named my_obj and assigning it to an object with three properties.
The next line uses the Object.keys() method to return an array of keys from the object and assigns it to a constant named all_keys.
A for loop is then used to loop through the array of keys. Inside the loop, the console.log() method is used to log the value of each key in the object to the console.
0 Comments