-1

I'm new to JavaScript and I've been stuck on this for a little while now. Let's say I have an object inside an array inside an object, like so:

         var myCrazyObject = { "name": "A ridiculous object", "some array": [7, 9, { purpose: "confusion", number: 123 }, 3.3], "random animal": "Banana Shark"}; 

Now I know that I can access the "some array" attribute thusly: myCrazyObject["some array"] So, the part that I'm stuck on is, how do I access the purpose or number attributes?

1 Answers1

2

It is the third element in your array, so you can access it by index:

myCrazyObject["some array"][2].purpose

or if you prefer the equivalent:

myCrazyObject["some array"][2]["purpose"]

would return "confusion". Obviously it's pretty brittle stuff. Normally you should be storing elements of the same type inside an array and not some integers at the beginning and then another arbitrary object. If for some reason the third element in this array wasn't an object you would get an error. So it's up to you to make the proper error handling here or fix your data input in order to bring some consistency here.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • That's true, I'm actually just working through some exercises in this book. Because I've never worked with an object like that before, I didn't know that the entire object was treated as one index, it wasn't really explained that way in the book. Thanks for that! – Nicholas Shoemake Feb 13 '15 at 20:59
  • *"I didn't know that the entire object was treated as one index"* It isn't (at least if I understood you correctly). `myCrazyObject["some array"]` returns an array, and how do you access the third element in an array? With `[2]`. So whether you do `var arr = myCrazyObject["some array"]; arr[2]` or `myCrazyObject["some array"][2]` doesn't make a difference. – Felix Kling Feb 13 '15 at 21:19