Jump to content

how to define a path when grabbing var from JSON?


ohdang888

Recommended Posts

var obj = {2:{"name":"Test for number 2", "other":"yup"},
4:{"name":"What i want!", "other":"yup"}
};

var test = 4;
alert(obj.test.name);// Would say "What i want"
var test = 2;
alert(obj.test.name);// Would say "test for number 2"

 

the variable "test" differs, so the path the values i'm looking for is differnt, how is this achieved?

 

Thanks!

 

You've created an array, so you simply reference it as an array element.

var obj = {2:{"name":"Test for number 2", "other":"yup"},
4:{"name":"What i want!", "other":"yup"}
};
var test = 4;
alert(obj[test].name);// Would say "What i want"
var test = 2;
alert(obj[test].name);// Would say "test for number 2"

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.