FAQ: Objects - Nested Objects

Hi!

Quick question, in the beginning of the lesson you declare objects thusly:

let spaceship = {};

But when declaring objects inside of objects they are declared thusly, with a parenthesis:

let spaceship = {
passengers: [{name: ‘Bobbo’}],

My question is, why aren’t objects inside of objects declared with:

let spaceship = {
let passengers = [{name: ‘Bobbo’}],

Or something like that? It seems to me that you’re declaring a function/method inside the object, what is the difference?

PS. Also on my earlier post i showed my code excerpts with a gray background and indented in the question, but my code here isnt, how do i post code here on the forums like code should look? If you understand what i mean, hehe DS

The main object, spaceship has a main property, passengers whose value is an array of objects.

obj = {
    prop: []
}

That permits all the passengers to be described with objects that have their name, rank, skills, etc.

While working through this lesson on nested objects and also having an object with a parameter that is an array of objects I was getting confused. When I was adding the objects to my Array I was trying to give each object in the array its own parameter name like below.

spaceship.passengers = ['Passenger One' = {},'Passenger Two' = {}, 'Passenger Three' = {name: 'Jane'}];

But when running that code it would not accept it as an answer. Would there ever be a need to have objects nested in an array to have their own parameter name as shown above? Or is it always going to be the case that doing something like the following will suffice?

spaceship.passengers = [{}, {},{name: 'Jane'}];  

And then when you need to access one of the objects in the array it would be done by using either dot or bracket notation to get to the array that is within the bigger parent object/objects. Then to access the different objects in the array it would be bracket notation with the index number of the object you are wanting?

That is invalid assignment within an array. An array can only contain values, not statements.

That is valid. We access those objects by their index.

spaceship.passengers[2].name  =>  Jane
1 Like

Ahh ok that makes sense thanks for the explaination @mtf

1 Like

dont know what is wrong

code i used:
let spaceship = {

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

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"

},

'back-up': {

  battery: "Lithium",

  terabytes: 50

}

}

};

let capFave = spaceship.crew.captain[‘favorite foods’][0];

let firstPassenger = spaceship.passengers[0];

here is an error:

/home/ccuser/workspace/object-literals-nested-objects/app.js:30
let capFave = spaceShip.crew.captain[‘favorite food’][0];
^

ReferenceError: spaceShip is not defined
at Object. (/home/ccuser/workspace/object-literals-nested-objects/app.js:30:15)
at Module._compile (module.js:571:32)
at Object.Module._extensions…js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:427:7)
at startup (bootstrap_node.js:151:9)
at bootstrap_node.js:542:3

edit:
i found my mistake.

above, it is written like spaceship. but i callled it with spaceShip

There is a typo in the defined variable name.

I am experiencing an issue with the Task 3 on lession 7 (Nested Objects).
I have successfully updated my nested passengers property with a nested array containing details of two passengers:

image

However when I attempt task 3, return the first passengers details, I am returned the entire passenger prop rather than the 1st passenger:

image
image

any advice of guidance on this issue would be gratefully received
Thanks

That’s because you have one object inside the array.

Consider,

spaceship.passengers = [
  {name: 'Dave', type: 'human', job: 'pilot'}, 
  {name: 'Frank', type: 'human', job: 'coPilot'},  
  {name: 'Hal9000', type: 'computer', job: 'systems'}
]

We do not need to name the objects in the array since we can access them by index.

This step one was the messiest so far in my opinion… could anyone explain also how it is an object {name: ‘Space Dog’}? so what’s the name of this object whats property and whats value? so “passengers” is property with array of objects (passengers: [{name: ‘Space Dog’}],) which look like normal pairs of key-value, but there are called objects hmm…? can any. Also I want to mention!!! to NOT USE so many exclamation marks in the course as it might be annoying… !!! thanks!! ! And guys

A JavaScript plain object consists of opening and closing curly braces to make the container, and it then has key-value pairs (called properties) to make up its content. It can have any number of these pairs.

tee = {
    color: 'green',
    size: 'large'
}

To access a property value we refer to it by its associated key.

tee['color']   //  green    (associative array notation)

or if we know the property exists we can use dot notation…

tee.color    //  green

We can only use dot notation when referring to the actual key name. Sometimes we don’t have the actual names but instead have the name in a variable.

for (key in tee) {
    console.log(`${key}: $(tee[key]}`
}

color: green
size: large

Now in the above lesson we have another object, but this time it is an array. An array IS an object, but it represents a linear data set whose keys are the indices. The array above contains a sequence of objects. Notice they have their own row, so to speak? Their indices are 0, 1, and 2 in that order.

Arrays are ordered from lowest to highest index. Plain objects have no specific order, and neither do they need it since they have unique keys that make it easy to access the values. An array must be iterated in order to locate a particular value.

When we run across the term object, it generally refers to the associative array, the plain object, { key: value }. In this lesson we are simply changing it up a little to show that an object can contain other objects, whether it is an array of objects, or an object of named arrays. Give yourself enough time to gradually absorb this and in due course it will be like child’s play.

1 Like

Yeah, thank you for your explanation, I was wandering why they are called objects with one pair, instead of properties, but actually every cell in that array is a column with possible more pairs so even so its like an object. BTW. did you moderate my post, as it might look I’m encouraging running with material?(there is so much more to learn in codding) Good understanding first. Codecademy is my choice, after trying yt and udemy didn’t work out for me(videos). Keep up good work guys, appreciated.

1 Like

No moderation that I can tell.

This is the Key for understanding the lesson, This quote should be the hint on that Chapter.

1 Like

Hey mtf! I have a query regarding your solution. I understood what you wrote but the instructions are to atleast write one key-pair, so…I want to know if its not necessary to write all 3 as key-pairs…Show me how to write another 2 without using key-pair.
I logged in after quite a long time so can’t remember the syntaxes well… Awaiting a positive response

What is the correct syntax for calling the method, in this case:

encourageTeam() { console.log('We got this!') }

  let spaceship = {
  passengers: [{name: 'Tom'},{name: 'John'}],
  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'] }
  },

console.log(spacesip.crew.captain.encourageTeam());

It doesn’t allow me.

1 Like

i understand the square brackets cause its an array,but why do we put the elements in that array each in the angle brackets?

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

This is reffering to assigning a new value to passenger key.

let spaceship = {
  passengers: [{firstInLine: 'friend1'}]
  telescope: {
    yearBuilt: 2018,
    model: "91031-XLT",
    focalLength: 2032 
  },

When I am describing passengers, why do I need to start my object literal with brackets over a set of curly brackets, whereas when describing telescope, I only require one set of curly brackets?

There is only the one telescope, but there can be many passengers. The array is meant to contain all of the passenger objects.

passengers: [{firstInLine: 'friend1'}, {second: 'Joe'}, {third, 'Jane'}]
1 Like

Agreed the Ruby Course is so much better than this one. If I had of started with this JS course I would have left by now.