JS JSON Pair Key & Value
This is the best way to get key and value from JS object:
function jkey(p){for(var k in p){return k;}}
function jval(p){for(var k in p){return p[k];}}
var myobj = {'Name':'Jack'};
alert(jkey(myobj)+' equals '+jval(myobj));
Or is there a more direct or faster way?
I need to make it so that I can name the keyname and value separately. functions work and return the name and value of the key, I was just wondering if there was a smaller, faster and better way.
Here's the best example: I want to get the key: value as separate variables ie {assistant: 'XLH'}, key = assistant, val = 'XLH';
I only use this when I know for sure that it is a pair and only returns one key and value.
formY={
tab:[
{
tabID:'Main',
fset:[
{
fsID:'Ec',
fields:[
{ec_id:'2011-03-002'},
{owner:'ECTEST'},
{assistant:'XLH'},
{ec_date:'14/03/2011'},
{ec_status:'Unreleased'},
{approval_person:'XYZ'},
]
}
]
}
]
}
+1
source to share
3 answers
To set an object from JSON in one line of code, I like to use the parseJSON jQuery method. Just pass in a JSON string and create an object for you. Then all you have to do is use your obj.Property object to access any value.
var myObj = '{"Name":"Jack"}';
var person = $.parseJSON(myObj);
alert(person.Name); // alert output is 'Jack'
0
source to share