1

When you have a multi-tiered object like a json object that say has 3 tiers

i = {'id':1{'name':'austin', 'lives':'college'{'name':'eckerd', 'major':'compsci'}}}

To reference the object is it better to reference it like so

for (x in i)
    i[x]['lives']['name']
//or
    i[x].lives.name

I think that gets my idea across. Pretty much use Associative arrays or the 'dot' method and why?

2 Answers 2

3

i[x].lives.name is equivalent to i[x]["lives"]["name"].

i[x][lives][name] means that you have variables called lives and name that you want to reference:

There's no real benefit to using one form over the other; imho it's clearest to use the dot notation unless you need the variable property names.

Sign up to request clarification or add additional context in comments.

4 Comments

err sorry those are supposed to be in quotes in the question
It's really just whatever you prefer. The two syntactical representations refer to the exact same objects in the exact same way. The method you choose will have no effect on your code besides the way it looks. Personally I use the . syntax to separate standard "objects" from what I consider to be "arrays" although to JS they are exactly the same thing.
@austinbv Looks good. Guess it's only the last line of this answer that's relevant then. :)
I'm tempted to downvote this as JSON keys (which are strings) should only be accessed accordingly as strings, not object parameters.
0

"Values can be retrieved from an object by wrapping a string expression in a [ ] suffix. If the string expression is a string literal, and if it is a legal JavaScript name and not a reserved word, then the . notation can be used instead. The . notation is preferred because it is more compact and reads better."

  • Crockford, D. (2008), JavaScript: The Good Parts. (pp. 21). Sebastopol, CA, U.S.A.: O'Reilly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.