Psl
Psl

Reputation: 3920

Jquery code to obtain the key name of a json data

I have a json data

jobs = [{
    "firstname": "myname"
}, {
    "place": "myplace"
}]

from this how can i print the key names "firstname" and "place"

$.each(jobs, function (key, value) {
    var name = value.firstname

});

what i want is in the output i have to print firstname : myname and place : myplace.I dont want to hard code firstname and place.i need to get it from json data itself.How it is possible

Upvotes: 2

Views: 118

Answers (7)

Roy M J
Roy M J

Reputation: 6938

Use :

$.each(jobs, function(key,value ) { 
   console.log(key+" : "+value);
});

Upvotes: 0

c.P.u1
c.P.u1

Reputation: 17094

No jQuery required. Using Object.keys

var jobs = [{
    "firstname": "myname"
}, {
    "place": "myplace"
}]

jobs.forEach(function(job) {
    Object.keys(job).forEach(function(key) {
        console.log(key + ':' + job[key]);
    });
});

jsFiddle Demo

Upvotes: 1

Avin Varghese
Avin Varghese

Reputation: 4370

Try this:

Fiddle: http://jsfiddle.net/kgBKW/

jobs = [{"firstname": "myname"}, {"place": "myplace"}];

$.each(jobs, function(key, value){
    $.each(value, function(key, value){
        console.log(key, value);
    });
});

Upvotes: 1

Krasimir
Krasimir

Reputation: 13529

You don't need to use jQuery for that.

var jobs = [{
    "firstname": "myname"
}, {
    "place": "myplace"
}]

for(var i=0; item=jobs[i]; i++) {
    for(var prop in item) {
        console.log(prop + ": " + item[prop]);
    }
}

Upvotes: 1

Kanishka Panamaldeniya
Kanishka Panamaldeniya

Reputation: 17576

try

$.each(jobs, function (key, value) {
   for(index in value)
   {
       alert(index);
       alert(value[index]);
   }
});

FIDDLE

Upvotes: 1

Rituraj ratan
Rituraj ratan

Reputation: 10378

var key= $.map(jobs , function(k,v){
    return k;
});

now key is array of key name

var value= $.map(jobs , function(k,v){
    return v;
});

now value is array of value name

now you can use this value as your desire way.....

Upvotes: 1

achakravarty
achakravarty

Reputation: 408

Use for in like

jobs.forEach(function(item){
    for(key in item){
        console.log(key);
        console.log(item[key])
    } 
})

Upvotes: 1

Related Questions