Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
190
rated 0 times [  196] [ 6]  / answers: 1 / hits: 19351  / 13 Years ago, fri, may 13, 2011, 12:00:00

suppose I have {data: {243232: {id: testid,name: test } }}



so when I do



var a = data.243232.id;
alert(a); // it gives me testid.



but when I do like



    var c = 243232; 
var d = data.c.id;
alert(d) //it gives as undefined.


so how to get correct value when i alert d in above case thanks.


More From » json

 Answers
276

Use the other notation var a = data['243232'].id



Remember all objects in JS are really just associative arrays.



Object keys just a variable in js and thus require proper naming



the variable naming rules are.




  • The first character must be a letter
    (either uppercase or lowercase) or an
    underscore (_), or a dollar sign ($).

  • Subsequent characters can be letters,
    numbers, underscores, or dollar signs
    in JavaScript Variables.

  • The JavaScript Variable name can't be
    a reserved word of JavaScript, see
    details of JavaScript Reserved
    Characters



JSON normally uses an eval() function to turn the string into a data-structure. This allows for incorrect keys. If you want to reference an improper key, you need to use the associative array method.



As for you addition



var c = 243232; 
var d = data[c].id;
alert(d) //it gives as undefined.


Will work


[#92261] Wednesday, May 11, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
parker

Total Points: 259
Total Questions: 109
Total Answers: 97

Location: Zambia
Member since Thu, Jun 25, 2020
4 Years ago
;