1

Is this the best way to get the key and value from a 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 ??

What I need to do is to me able to call the key-name and value seperately. the functions work and return the keyname and value, I just wondered if there was a smaller, faster, better way.

Here's a better example, I want to access the key:value as separate variables i.e {assistant:'XLH'}, key=assistant, val = 'XLH';

I only use this when I know for sure that it is a pair and only returns a single 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'},
                        ]
                    }
                ]
        }
        ]
}
crankshaft
  • 2,607
  • 4
  • 45
  • 77
  • 3
    This is not JSON. This is a JavaScript object literal. Also your functions would not work if the object has more than one property and could give you even wrong results. What exactly do you want to do? – Felix Kling Mar 14 '11 at 09:23
  • According to [JSON spec](http://www.json.org/) string in JSON **has to** be surrounded with **double quote** characters. Apostrope characters are not valid. – Grzegorz Gierlik Mar 14 '11 at 09:29
  • 1
    It can't include operators, functions or a bunch of other things either. This is JS with a JS object literal (as Felix said). Nothing to do with JSON. – Quentin Mar 14 '11 at 09:39

3 Answers3

1

It would be better to avoid looping the object twice. You could do this:

function getKeyValue(obj) {
    for(var key in obj) {
        if(obj.hasOwnProperty(key)) {
            return {key: key, value: obj[key]};
        }
    }
}

and call it with:

var kv = getKeyValue(obj);
alert(kv.key + ' equals ' + kv.value);
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

For setting an object from JSON in a single line of code I like using the jQuery's parseJSON method. Just pass in your JSON string and it creates the object for you. Then all you have to do is use your obj.Property to access any value.

var myObj = '{"Name":"Jack"}';
var person = $.parseJSON(myObj);
alert(person.Name);  // alert output is 'Jack'
0

I'm finding your question is a little unclear, but I suspect you are looking for:

var myobj = {'Name':'Jack'};

for(var k in myobj){
    if (myobj.hasOwnProperty(k)) {
        alert(k + ' equals ' + myobj[k]);
    }
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335