FAQ: Objects - Nested Objects

I was testing the code to access a property of an object in the array of an object :woozy_face: and this is the result, I hope it helps someone.

let spaceship = { passangers: [{jonSnow: {height: 170, age: 36}}, {tyrion: {height: 135, age: 53}}] }; let secondPassanger = spaceship.passangers[1].tyrion.height; console.log(secondPassanger); //Print: 135

Why isn’t this a valid JS syntax?

spaceship.passengers = [
  'passenger 1': {
    name: 'Tom',
    age: 30
  },
  'passenger 2': {
    name: 'Gustav',
    age: 29
  },
   'passenger 3': {
    name: 'Mary',
    age: 34
  }
];

Why isn’t this valid too? It works if I make them nameless (that is, remove passengerOne and so on), but how do I list objects that have a name in JavaScript? :thinking:

[
  let passengerOne = {
    name: 'Tom',
    age: 30
  },
  let passengerTwo = {
    name: 'Gustav',
    age: 29
  },
   let passengerThree = {
    name: 'Mary',
    age: 34
  }
];

The let keyword is not valid in an array, and neither is assignment.

const passengers = [
  {
    name: 'Tom',
    age: 30
  },
  {

  },
  {

  }
]
 > passengers[0].name
<- Tom
1 Like

¿What is the purpose of placing objects in an array with key: value pairs?

and

¿Why the syntax is

firstPassenger = [{name: "x"}];  

instead of

firstPassenger = [object: {name: "x"}];  

?

Consider,

passengers = [
  {name: "X", age: 30},
  {name: "Y", age: 30},
  {name: "Z", age: 30}
];  

Above we have an array of objects which is useful when we don’t want to have a whole bunch of named objects. It is orderly, easy to access and all the objects are in one place.

As for your other example, it is invalid and throw an error, either syntax or runtime.

1 Like

Ok, know i understand. I read again the concept of object literals and also the syntax, now it makes sense.

1 Like

The problem here is definitely in the way exercise is written. It lacks context as to why object would be even written as an array to begin with. Without that it’s easy to miss that you need to write an actual array in the first place. A big point is made in previous exercises that objects can have multiple objects within them, only to flip this in this step and say, no make an array for these items. A simple line such as: ‘you don’t care so much about properties for passengers, so you will just list them as an array’ would suffice.

Here is a question that is not on this exercise, but I wanted to know what would the code look like if we wanted to log the “Lithium” by using Nested Objects.? I tried doing **console.log(spaceship = [‘back-up’].battery); but the result was ‘undefined’. Thoughts?

In order to explore this we would benefit greatly from having the object you are working from in full view. Please post you complete spaceship object.

Apologies, it is this excercise:
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”
},
‘back-up’: {
battery: “Lithium”,
terabytes: 50
}
}
};

1 Like

Okay, so we need to traverse the object to the battery property:

spaceship['back-up'].battery

The square brackets are necessary because of the dash character. If we were to remove the dash, then we could use dot notation.

spaceship.backup.battery

So if I understood you correctly, either one of these two you mentioned should log to the console? Which will result in "Lithium’?

1 Like

Assuming we use them as the argument to console.log(). The dot notation will only work if you change the property name in the object to, backup.

Hello, I made this work the way they wanted like this:
passengers: [
{
name: [‘Neil’, ‘Michael’]
},
{
surname: [‘Armstrong’, ‘Collins’]
}
]
So basically, passengers is an array of 2 objects, each object has an array.
To access the first name:

let firstPassenger = spaceship.passengers[0].name[0];

console.log(firstPassenger) // prints Neil
Hope this helps, though am years late.

Hello All,

I took this exercise a little farther than I should have. I thought I would share it though. I really wanted to see if I could pull whatever I wanted from the nested objects.

Let me know your thoughts?

let spaceship = { passengers: [ {name: 'Jim', job: 'Florist'}, {name: 'Sarah', job: 'Artist'}, {name: 'Jessy', job: 'Student'} ], 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 passengerList = () => { //I learned about the for in loop for objects in the next lesson. for (let passenger in spaceship.passengers) { console.log(spaceship.passengers[passenger].name); } //The standard for loop works the one above I think is how you are suppose to do it. // for (let i=0; i < spaceship.passengers.length; i++) { // console.log(spaceship.passengers[i].name); // } } let capFave = spaceship.crew.captain['favorite foods'][0]; let firstPassenger = spaceship.passengers[0]; console.log(`The Captain of this ship is ${spaceship.crew.captain.name}. Her favorite food is ${capFave}. There are currently ${spaceship.passengers.length} passengers onboard.`); console.log('The passengers are as follows:'); passengerList();
2 Likes

We know that in order to access an Object’s properties we can either use the dot or the bracket notation. I prefer the later since it can be used in wider range of cases. But when I write

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

it throws an error : - ReferenceError: crew is not defined at Object.. Please explain where I am going wrong? Thanks.

check the quotation marks.

spaceship.crew.captain['favorite foods'][0] 

would be the same as

spaceship['crew']['captain']['favorite foods'][0] 

in JavaScript.

error

The error is saying that there’s no crew variable (created by let crew or something like that earlier).

1 Like

It works. Thanks for clarifying @java9731188620. I thought we only need quotation marks if it contains more than one word or has some special characters.

Regards
Prabir

I am having a bit of trouble with the semantics of an object. In the lesson review it states "

  • Objects store collections of key-value pairs.
  • Each key-value pair is a property—when a property is a function it is known as a method.
  • An object literal is composed of comma-separated key-value pairs surrounded by curly braces. "

In problem two the task asks for - Right now the passengers property has a value of null . Instead, assign as its value an array of objects. These objects should represent the spaceship ‘s passengers as individual objects. Make at least one passenger object in the array that has at least one key-value pair on it.

The hint shows - passengers : [{name: ‘Space Dog’}]

In my interpretation passengers would be an ‘object literal’, the square brackets indicate an array, and inside the array is a key:value pair. Aren’t the key value pairs inside of an object called properties? Why is this an array of objects?

Thank you!