DEV Community

Morris John
Morris John

Posted on

Is it possible to nest an array in a JavaScript object?

So I've gotten to JavaScript objects and it's very cool. Almost cooler than arrays but I've got an issue. I know it's possible to nest objects in arrays and I've done them but I can't seem to do it the other way round.

I've googled this and I haven't gotten a satisfactory response.

Thanks.

Top comments (5)

Collapse
 
1e4_ profile image
Ian

What have you tried so far?

const obj = {
    an_array: []
}

Should work

Collapse
 
morrisjohn profile image
Morris John

What I've been trying to do is

...

var yes = {
Name: "Morris",
Age: 21

no = [22, 11, 1998]

};

I've been trying to do the opposite of how you nest objects in Arrays. I'm using Colt Steele's course and he said it's possible to nest objects in arrays but he only showed the other way round.

Forgive me I'm just learning

Collapse
 
1e4_ profile image
Ian • Edited

Formatting requires 3 backticks (`) not apostrophe (') fyi.

And that code won't work as you are missing some commands, each item in an object must be separated by a comma, also there is no =, you use a colon (:)


var yes = {
name: "Morris",
age: 21,
no: [22, 11, 1998]
};

Thread Thread
 
morrisjohn profile image
Morris John

Thanks. I can't believe the difference between = & : almost made me pull my entire hair out.

I saw mistake was declaring the array within the object with an equal sign (=) instead of a colon(:).

Thanks man

Collapse
 
roelofjanelsinga profile image
Roelof Jan Elsinga

What Ian said is the correct answer. An object needs properties and those properties can have any value. So the property in Ian's answer is "an_array" and the value is the actual array. To retrieved this array in your code, you'd have to use: obj.an_array