0

I am trying out JavaScript objects, and I'm just stuck on why I am getting a TypeError in my code.

var marvelFunFact = {
    captainMarvel: [
        {
            info: "Did you know that info 1",
            imageUrl: "url.com/image1.jpg"
        },
        {
            info: "Did you know that info 2",
            imageUrl: "url.com/image2.jpg"
        },
        {
            info: "Did you know that info 3",
            imageUrl: "url.com/image3.jpg"
        }
    ],
    lastName: "Doe",
};
var marvelFunFactContext = "captainMarvel";
var rand = marvelFunFact.marvelFunFactContext[Math.floor(Math.random() * marvelFunFact.length)].info;

The error that appears is "TypeError: marvelFunFact.marvelFunFactContext is undefined". I am only a beginner, don't judge, this is probably just a simple fix :/

NeuronButter
  • 709
  • 1
  • 8
  • 24
  • 1
    `marvelFunFact.marvelFunFactContext` you're trying to access the object property `'marvelFunFactContext'`. You want to use the bracket notation instead: `marvelFunFact[marvelFunFactContext]` – briosheje Jul 02 '19 at 10:27
  • `marvelFunFactContext` is not a property of `marvelFunFact`, it is instead a separate variable – Nick Parsons Jul 02 '19 at 10:28
  • @VLAZ oh; I would've put this one instead: https://stackoverflow.com/questions/4255472/javascript-object-access-variable-property-by-name-as-string but still... – briosheje Jul 02 '19 at 10:29
  • @briosheje eh, both are about the same thing. Either would have worked. I actually used to link to https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets but then realised a much better dupe was available. – VLAZ Jul 02 '19 at 10:30
  • I guess the problem is that there are **way too many duplicates** of that one specifically. Still, it's worth to note that the question itself was properly exposed. – briosheje Jul 02 '19 at 10:32

0 Answers0