I was testing the code to access a property of an object in the array of an object and this is the result, I hope it helps someone.
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?
[
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
¿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.
Ok, know i understand. I read again the concept of object literals and also the syntax, now it makes sense.
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.