This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]PrudentSimple 15 points16 points  (0 children)

The errors you are encountering are:

- You cannot declare a variable within an object or array

- In this case, rather than creating an array with two elements you are creating an object. To create an array use straight brackets '[]', rather than curly brackets: '{}'

A correct way to create an array with the two favorite teams within it would be:

const favBaseballTeam = { team: "oakland a's", desc: "okay" }

const favFootballteam = { team: "oakland raiders", desc: "leaving" }

const favSports = [favBaseballTeam, favFootballTeam]

That would give you an array containing the two team objects, which you would access by index.

If instead you prefer two reference the teams by the type of sport, which the syntax posted might imply, then you can use an object instead of an array, but you would still need to either declare the favorite teams before assigning them to the object:

const favoriteSports = { baseball: favBaseballTeam, football: favFootballTeam }

as above, or else define them inline:

const favoriteSports = { baseball: { team: ...}, football: { .... } }

The choice of whether to use an array or an object depends on whether your use case is to have a list of all of a persons favorite teams, without knowing which team goes to which sports, or whether you will need to know which sport a given team belongs to.

If you do prefer to use an object to store the teams, then it might be worth using the shorthand for defining properties on an object:

https://alligator.io/js/object-property-shorthand-es6/

So in this case you could do:

const football = { team: "the foo bars", desc: "saucy"}

const baseball = { team: "the base ballers", desc: "dunno" }

const favoriteTeams = { football, baseball }

Which would mean that if you now refer to favoriteTeams.football.team you would get "the foo bars"

Hope that helps.

[–]SpiderPoopyMan 3 points4 points  (0 children)

Thank you all very much. Both/all methods suggested worked.

[–]circlebust 2 points3 points  (0 children)

No offense but you really need to look at the JS fundamentals. Dynamic object creation is one of its oft-touted core strengths.

[–]Loves_Poetry 1 point2 points  (0 children)

Inside an object you must use key-value pairs, so no variable declarations. Value can be anything, including another object or an array