Generate an Array of All Object Keys with Object.keys()

Tell us what’s happening:

I have a good understanding on how to use Object.keys() with 1 object; however, I want to understand how this would work in a nested array with 2 or more objects.

  **Your code so far**
let users = {
Alan: {
  age: 27,
  online: false
},
Jeff: {
  age: 32,
  online: true
},
Sarah: {
  age: 48,
  online: false
},
Ryan: {
  age: 19,
  online: true
}
};

function getArrayOfUsers(obj) {
// Only change code below this line
return Object.keys(obj);
// Only change code above this line
}

console.log(getArrayOfUsers(users));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36

Challenge: Basic Data Structures - Generate an Array of All Object Keys with Object.keys()

Link to the challenge:

This is merely one of the tasks I need to complete for JS - basic data structure. I was just curious as to how you would deal with two objects using Object.keys().

For example, how would you generate an array for the second object without including the first one:

let users = {{
Alan: {
  age: 27,
  online: false
},
Jeff: {
  age: 32,
  online: true
},
}

London: {
numberOnline: 4653
},

Tokyo: {
numberOnline: 5968
}
};

I have a few simple examples:

let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  }
};

// To get an array of the keys of the user `Jeff`, I could write:
console.log(Object.keys(users.Jeff)) // [ 'age', 'online' ]

// If I want to use `Object.keys()` to see all the users' key's values, I could write:

const userNames = Object.keys(users);
for (let i = 0; i < userNames.length; i++) {
  const user = userNames[i];
  console.log('user: ' + user);
  const userKeys = Object.keys(users[user]);
  for (let j = 0; j < userKeys.length; j++) {
    const key = userKeys[j];
    console.log('  ' + key + ': ' + users[user][key]);
  }
}

The nested for loops produce:

user: Alan
  age: 27
  online: false
user: Jeff
  age: 32
  online: true
2 Likes

I appreciate the time you took to help me understand this Randall!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.