user2518389
user2518389

Reputation: 19

Get value of variable in order to get value from dictionary in javascript

I have a big JSON string which I have encoded into javascript objects. It looks like so:

{"stdout": "", 
"line": 23, 
"func_name": "<module>", 
"stack_to_render": [
    {"is_parent": true, 
    "ordered_varnames": ["__init__", "__qualname__", "num", "player", "__return__"], 
    "is_zombie": true, 
    "encoded_locals": {"__qualname__": "Team", "player": ["REF", 3], "__init__": ["REF", 2], "__return__": ["REF", 1], "num": 5}, 
    "frame_id": 1, 
    "unique_hash": "Team_f1_p_z", 
    "func_name": "Team", 
    "is_highlighted": false, 
    "parent_frame_id_list": []}], 
"ordered_globals": ["Team", "i_type", "s_type", "l_type", "t_type", "d_type",         "o_type", "make_squares"], 
"globals": {"s_type": "hello", 
    "o_type": ["REF", 8], 
    "l_type": ["REF", 5], 
    "make_squares": ["REF", 9], 
    "Team": ["REF", 4], 
    "d_type": ["REF", 7], 
    "i_type": 3, 
    "t_type": ["REF", 6]}, 
"heap": {"1": ["DICT", 
            ["__qualname__", "Team"], 
            ["player", ["REF", 3]], 
            ["__init__", ["REF", 2]], 
            ["num", 5]
          ], 
    "2": ["FUNCTION", "__init__(self)", 1], 
    "3": ["FUNCTION", "player(self, name)", 1], 
    "4": ["CLASS", "Team", [], ["__init__", ["REF", 2]], 
            ["__qualname__", "Team"], ["num", 5], ["player", ["REF", 3]]], 
    "5": ["LIST", 1, 2, 3, 4, 5, 6, 7, 8, 9], 
    "6": ["TUPLE", 2, 3], 
    "7": ["DICT", ["dictionary", 1]], 
    "8": ["INSTANCE", "Team", ["logo", null], ["members", 0]], 
    "9": ["FUNCTION", "make_squares(key, value)", null]}, 
"event": "return"}]}'

Let's say,

var dict = "That dictionary ^^"

I have the following code:

var name = dict.ordered_globals[i]; //Let's say returns "Team"

var ref = dict.globals.name;        
alert(ref[1]); //Should alert 4`

It's throwing undefined because there is no .name key value in the dictionary. What I want it to do is treat dict.globals.name as dict.globals.Team.

Upvotes: 2

Views: 254

Answers (2)

Instance Noodle
Instance Noodle

Reputation: 227

if you use var ref = dict.globals.name; it'll treat the name as one of the properties of dict.globals, but dict.globals does not have the name property at all, in case that you want to retrieve a property of an object but you don't know exactly the property name or it can be changed at runtime, if that such a case then the literal key come in hand var ref = dict.globals[name]. hope this help

Upvotes: 0

tom
tom

Reputation: 19153

You need to do:

var ref = dict.globals[name]

Otherwise, name is treated as a literal key, instead of the string stored in the name variable. You want the latter.

Upvotes: 3

Related Questions