2

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

Arturs
  • 1,258
  • 5
  • 21
  • 28
Psl
  • 3,830
  • 16
  • 46
  • 84
  • http://stackoverflow.com/questions/5572708/get-name-of-key-in-key-value-pair-in-json-using-jquery?rq=1 check this you will get idea how to do this – Satyam Koyani Aug 30 '13 at 05:34
  • @Psl , See my answer. Edited it so that you dont have to hard-code first name n place. It will get it from json – Roy M J Aug 30 '13 at 05:53

7 Answers7

1

Use for in like

jobs.forEach(function(item){
    for(key in item){
        console.log(key);
        console.log(item[key])
    } 
})
achakravarty
  • 418
  • 3
  • 7
1

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);
    });
});
Avin Varghese
  • 4,340
  • 1
  • 22
  • 31
1
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.....

Rituraj ratan
  • 10,260
  • 8
  • 34
  • 55
1

try

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

FIDDLE

Kanishka Panamaldeniya
  • 17,302
  • 31
  • 123
  • 193
1

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]);
    }
}
Krasimir
  • 13,306
  • 3
  • 40
  • 55
1

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

c.P.u1
  • 16,664
  • 6
  • 46
  • 41
0

Use :

$.each(jobs, function(key,value ) { 
   console.log(key+" : "+value);
});
Roy M J
  • 6,926
  • 7
  • 51
  • 78