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,261
  • 5
  • 21
  • 28
Psl
  • 3,602
  • 13
  • 43
  • 78
  • 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,212
  • 1
  • 19
  • 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
  • 9,947
  • 8
  • 33
  • 52
1

try

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

FIDDLE

Kanishka Panamaldeniya
  • 16,732
  • 29
  • 117
  • 190
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,032
  • 3
  • 39
  • 54
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
  • 15,958
  • 6
  • 43
  • 40
0

Use :

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