Skip to content Skip to sidebar Skip to footer

Js Json Pair Key & Value

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':'J

Solution 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);

Solution 2:

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'

Solution 3:

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]);
    }
}

Post a Comment for "Js Json Pair Key & Value"