2

I have a lot of json data fetched from a SQL databases similar to this one below:

var data = [
        {"id": 0, "gender": "male", "name": "joan"},
        {"id": 1, "gender": "female", "name": "pep"},
        {"id": 2, "gender": "female", "name": "maria"},
        {"id": 3, "gender": "female", "name": "meli"},
        {"id": 4, "gender": "female", "name": "jaume"}
            ];

How can I get in Javascript (jQuery or underscore.js would be better)?

keys = ["id", "gender", "name"];

(sorry for duplicates, I couldn't find something exactly like this)

UPDATE: Yes this can be considered a duplicate if you take the first element of the data array, this is: data[0]

Then, the shortest given solution (using underscore.js) is

keys = _.keys(data[0]);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
jaumetet
  • 86
  • 7

2 Answers2

2

using jquery.each you can get the key of json objects

     var keys = [];

    $.each(data[0], function(key, value){
         console.log(key); // id, gender, name
         console.log(value); // 0, male, joan
         keys.push(key);
        });

console.log(keys); // ["id", "gender", "name"]

Cloud Newbie
  • 61
  • 1
  • 6
1

If all objects have the same keys, jquery.map might be useful:

keys = $.map(data[0], function(val, key) { return key })

For a pure javascript solution consider Object.keys

georg
  • 211,518
  • 52
  • 313
  • 390