1

I'm looking to pass a string into a function and return the json object of that string name.

Objname is a string, such as "ky1"

function myFunction(objname) {
    return myjsonobj.objname;
}

How can I get the above to parse correctly? This is a simplified example, but demonstrates what I'm trying to achieve.

I'm not using jQuery, this is not an option for me in this piece of work.

Any help would be great, thanks!

Dave Harding
  • 481
  • 1
  • 4
  • 19
  • Use `[` and `]` around it, like `myjsonobj[objname]` – TheZ Jul 09 '12 at 22:18
  • exact duplicate of [Accessing property of object with variable](http://stackoverflow.com/questions/11230063/accessing-property-of-object-with-variable) and _many others_ – Alnitak Jul 09 '12 at 22:20
  • possible duplicate of [Using string from variable as property name for JSON in Javascript?](http://stackoverflow.com/questions/9612686/using-string-from-variable-as-property-name-for-json-in-javascript) and many others. – Bergi Jul 09 '12 at 22:20
  • BTW, this is not "JSON", it's a Javascript _Object_, which when serialised into a string then becomes JSON. – Alnitak Jul 09 '12 at 22:22

2 Answers2

2

try with

return myjsonobj[objname];

if you write that with dot notation you're looking for a key named exactly "objname" but in your example it is only a variable.

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
0

I think this is what you are going for. You can index the property with square brackets and it is the same thing as the period notation.

myjsonobj["ky1"] == myjosnobj.ky1


function myFunction(objname) {
    return myjsonobj[objname];
}
Jeff
  • 13,943
  • 11
  • 55
  • 103