Is there a native JavaScript way to iterate through an JavaScript object like the following one? It seems like “.forEach(fn)” is only working for arrays. I'm looking for a simple way to solve this.
var myObject = {
"1": {
"username": "peter",
"userGroup": "User"
},
"2": {
"username": "petra",
"userGroup": "Admin"
}
}
There is a nice native JavaScript way to solve this. Simply use “Object.keys()” on your JavaScript object which will return an associative array. On this array you are able to use “.forEach()” on the result:
var myObject = {
"1": {
"username": "peter",
"userGroup": "User"
},
"2": {
"username": "petra",
"userGroup": "Admin"
}
}
// loop through object
Object.keys(myObject).forEach(key => {
console.log(key); // the current key.
console.log(myObject[key]); // the value.
});