I don’t know what wrong in this:
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
let arr=[...obj];
return arr.keys();
// 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/69.0.3497.100 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
This line:
let arr = [...obj];
The ...
syntax takes something that is iterable and basically goes through its values one by one. By putting in []
you are saying “take this iterable and convert it to an array”.
Iterable is something that you can iterate through, something with items in order, so an array-like thing. Arrays are iterable, so are strings (first character, second character, third character and so on).
Objects are not iterable: they have no order (edit: note that technically they do: integer keys in ascending order followed by string keys in insertion order, but they still aren’t iterables). This:
{ foo: 1, bar: 2}
Is effectively exactly the same as:
{ bar: 2, foo: 1}
So the let arr = [...obj]
line doesn’t make sense, it’s a syntax error.
The Object.keys()
function takes an object and returns all its keys in an array. Note that it’s written like that: it’s just a static function, Object.keys(someObjectYouWantTheKeysOf)
. So like:
> Object.keys({foo: 1, bar: 2})
['foo', 'bar']
Similarly, just for reference, there are two other similar functions:
> Object.values({foo: 1, bar: 2})
[1, 2]
> Object.entries({foo: 1, bar: 2})
[['foo', 1], ['bar', 2]]
4 Likes