FAQ: Objects - Nested Objects

This community-built FAQ covers the “Nested Objects” exercise from the lesson “Objects”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Introduction To JavaScript

FAQs on the exercise Nested Objects

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

While doing the practices, I have a syntax problem of replacing a nested object’s value with an array.

Suppose there is a nested object inside the spaceship object:

let spaceship = {
passengers: null
}

When asked to replace the null value with an array, I wrote:

let spaceship = {
passengers: {[‘A’]}
}

My answer is incorrect, and the correct answer is:

let spaceship = {
passengers: [{‘A’}]
}

Why should the brackets encircle the curly brackets, but not the other way around?
It doesn’t seem resursive in construction.

Could anyone help explain this syntax?

9 Likes

Step 2 is quite ambiguous in it’s instruction. No where does it say that you have to change the original nested object.

Also this code should work just as well as editing the original spaceship object especially since it re-enforces the previous lesson’s objectives of assigning and re-assigning object properties

spaceship.passangers = [{
    name: 'Space Dogs'
}];

Please let me know if this is something that is valid or not regardless if it doesn’t follow the instructions explicitly.

22 Likes

The exercise expects us to modify the object using line calls, not direct edits.

spaceship.passengers = [{1:'Tom'}, {2:'Jerry'}, {3:'Jane'}];
13 Likes

If I am reading your code correctly, you are assigning an object literal to passengers with a single element array as the key with no value. I don’t think that is a valid way to assign a key identifier within an object since a key can only be a string since it identifies the value held within that key (though I could be wrong since I know very little Javascript though the logic does make sense).

If you coded the assignment this way it should be valid but once you reference the key, it would evaluate to undefined because there is no value associated with it:

let spaceship = {
    passenger: {'[A]'}
}

The reason why the “correct” answer works is because you are assigning the passengers key to an array that has an object as it’s first element and that element gets invoked when you assign it to a variable:

let firstPassenger = spaceship.passengers[0];
1 Like

For step 3, I wrote:

spaceship.passengers=[{passOne: {name: 'John'}}, {passTwo: null}, {passThree: null}];
let firstPassenger=spaceship.passengers[0];
console.log(firstPassenger);

which worked fine, except that my return was:
{ passOne: { name: 'John' } }
How would I format the code so that my return would just be John? i.e. How do I return a value within an object which is an element in an array, which is itself a value in an object?

2 Likes

@ironsidezer0 Throughout the Introduction to JavaScript course I’ve found a few mistakes in the instructions like putting code outside of a block when it was supposed to be inside and things like that. I think this lesson also has an error. I was also trying to get the console to log just the first name and not

{ name: ['name1', 'name2']}

So I was reading through the instructions and saw that it asks us to replace the key passengers’ value to an array, then when we call

spaceship.passengers[0]

since we put

{ name: ['name1', 'name2']}

inside of that array in index0, when we try to log

spaceship.passengers[0]

it logs

{ name: ['name1', 'name2']}

as if it were a string.

Instead, I replaced the null value with an object (I removed the [ ] surrounding

{ name: ['name1', 'name2']}

and then logged

spaceship.passengers.name[0]

which gave me what I wanted: name1. This is how I wrote the last bit of the code to get the name I wanted logged to the console:

spaceship.passengers =
  	{
     name: ['Neil', 'Michael'],
     surname: ['Armstrong','Collins']
    };

const firstPassenger = spaceship.passengers.name[0] + ' ' + spaceship.passengers.surname[0];


console.log(firstPassenger);

The output was what I wanted: Neil Armstrong. Hope this helps!

11 Likes

This makes more sense than their hints did. Thanks!

4 Likes

Hi
The code you wrote is not what the instruction wants! it wants us to re-assign passengers to an array of objects not an object of arrays (wich you did!) this code can do the same thing but I thing the purpose is to teach us how to change object’s properties and write objects in arrays.

2 Likes

Hi. I know it’s not what they ask for in the instructions. That’s why I mentioned I’ve found various instructions that are actually wrong. I couldn’t get what I wanted the way it was asked there, so I tried another way. But if you figured it out the way they ask, please share. I’d love to know how it’s done!

The solution says otherwise. I wonder why.

1 Like

I see by looking at the hint just now that it is a direct edit. Totally read that wrong when I did the exercise way back when and wrote a statement assigning a populated list to the attribute.

spaceship.passengers = [{1:'Tom'},{2:'Jerry'},{3:'Jane'}];

The SCT passed that step so must have just polled the property to see if it was set. How we set it is irrelevant, just so it is set.

5 Likes

Hi can somebody explain why its:

passengers:[{name: ‘Space Dog’}]

and not

passengers:{[name: ‘Space Dog’]}

Really appreciating it and thank you.

3 Likes

That is an improper array.

The idea is an array of objects, in this case, not an object of arrays.

5 Likes

This syntax seems to imply that passengers is a property of an object. In this example you are assigning an array as the value of the passengers property. That array contains an object, and in theory will eventually be an array of many similar objects.

This will raise an error. If you wanted an object as the value for the passengers property, it would have to look like this:
passengers: {name: "spacedog"}

1 Like

let spaceship = {
passengers: null,
telescope: {
yearBuilt: 2018,
model: “91031-XLT”,
focalLength: 2032
},
crew: {
captain: {
name: ‘Sandra’,
degree: ‘Computer Engineering’,
encourageTeam() { console.log(‘We got this!’) },
‘favorite foods’: [‘cookies’, ‘cakes’, ‘candy’, ‘spinach’] }
},
engine: {
model: “Nimbus2000”
},
nanoelectronics: {
computer: {
terabytes: 100,
monitors: “HD”
},
backup: {
battery: “Lithium”,
terabytes: 50
}
}
};
let capFave = spaceship.crew.captain[‘favorite foods’];

1 Like

can’t assign capFave to the requested value
i’m officially drained out of ideas :thinking:
been brute-forcing for a while now

//ideas
let capFave = spaceship.crew.captain."favorite foods"[0];
let capFave = spaceship.crew.captain."favorite foods".[0];
let capFave = spaceship.crew.captain."favorite foods".0;
let capFave = spaceship.crew.captain."favorite foods"(0);
let capFave = spaceship.crew.captain."favorite foods".(0);
let capFave = spaceship.crew.captain['favorite foods[0]'];
let capFave = spaceship.crew.captain['favorite foods.[0]'];
let capFave = spaceship.crew.captain.['favorite foods[0]'];

to access array we use arrayIndex[0], if I change
key to favoritefoods with one word, I can get access, but that’s not what the task is

favoritefoods: [‘cookies’, ‘cakes’, ‘candy’, ‘spinach’] }
let capFave = spaceship.crew.captain.favoritefoods[0]; //cookies

4 Likes

You’ve gotten close. To reference nested objects with key names that include more than one word, you do need the square brackets. Then you want the the first value in the array that makes up the value for that key. So…
let capFave = spaceship.crew.captain['favorite foods'][0]; will probably work :wink:

Note that if 'favorite foods' had been 'favoriteFoods', you would be able to reference the same value like so: spaceship.crew.captain.favoriteFoods[0]

11 Likes

let capFave = spaceship.crew.captain['favorite foods'][0];
yeah, I was pretty close :laughing:

6 Likes

Wow. Step 2 in this contains some really interesting grammar:

“Make at least one passenger object in the array that has at least one key-value pair on it.”

That makes no grammatical sense whatsoever. I can guess as to the intended meaning but my goodness someone needs to edit these exercises a lot better.

11 Likes