How to loop through a JavaScript object with the objects as items?

JavaScript

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"
    }
}
Programming Computer Question created: 2020-10-10 05:36 Penguin

7

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.
});
answered 2020-10-10 05:42 darkOrbit