In Javascript you can iterate over the properties of an object using a for in
loop. If we have the following javascript object with two string properties name
and lastname
:
let obj = {
name: 'Peter',
lastname: 'Rasmussen'
}
We can iterate over each property and get its value using a for in
loop:
for (let prop in obj){
console.log(prop, obj[prop]);
}
In the above prop
is the property name (name
, lastname
) of the object and since javascript objects can be accessed like dictionaries we can access the value of the property (Peter
, Rasmussen
) using obj[prop]
. Essentially calling obj['name']
and obj['lastname']
which is the equivelant as obj.name
and obj.lastname
The above will print name Peter
and lastname Rasmussen
.
That is all!
I hope you found this helpful, please leave a comment down below if I forgot something!