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

Tell us what’s happening:
j
don’t get it

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) {
  // change code below this line

  // change code above this line
}

console.log(getArrayOfUsers(users));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/generate-an-array-of-all-object-keys-with-object-keys

1 Like

Basically the solution is given for you in the instructions where it says,

Object.keys()

You will want to return keys of any object (object parameter) that is passed within the function.

return Object.keys(obj);

6 Likes

HI I am still having problem with my code with the example you gave @shimphillip it states that object is undefined. What am I doing wrong cause I write return object.keys(obj); but object is said to be undefined.

It’s capital O in object.

2 Likes

In order to get keys of any object the syntax is Object.keys(<object_name>). This returns an array.

In this challenge we have a nested Object,meaning we have keys which also contains objects and we need to list them all.

Here is the function that I wrote to get all the keys:

function getArrayOfUsers(obj) {
// change code below this line
let newArr = [];
for(let user in obj){
newArr.push(user); //Here I am also adding the first level keys (Alan, Jeff, Sarah and Ryan with each iteration.
newArr.push((Object.keys(obj[user]))); //Here I am adding the keys of Alan, Jeff, Sarah and Ryan with each iteration
}

return newArr; //Returning the array to calling function.

// change code above this line
}

I’m glad you explained that, @shimphillip!

My brain just said “No, it’s not going to be that simple,” and then just said what the heck are you supposed to do here?! Haha, I’ve got to stop overestimating a challenge on here.

2 Likes

The O is capital, also you are supposed to pass in the “users” object, not the “obj”

return Object.keys(obj);
1 Like

i have done the same but used console.log instead of return and did not work, just noticed how it matter to use return and not console.log!
im wondering whats the difference between both!

console.log just print a value to the console. return is needed for the function to output a value

1 Like

Dude, the answer is in your title: [Generate an Array of All Object Keys with Object.keys()]