Hikaru Shindo
Hikaru Shindo

Reputation: 2913

How to get all key in JSON object (javascript)

{"document":
  {"people":[
    {"name":["Harry Potter"],"age":["18"],"gender":["Male"]},
    {"name":["hermione granger"],"age":["18"],"gender":["Female"]},
  ]}
}

From this JSON example, I would like to get the keys such as name, age, gender for each people.

How to do this?

Upvotes: 44

Views: 272080

Answers (7)

Jeeva
Jeeva

Reputation: 1057

I use Object.keys which is built into JavaScript Object, it will return an array of keys from given object MDN Reference

const person = {
  name: "Jeeva",
  age: "22",
  gender: "Male"
}
console.log(Object.keys(person))

Upvotes: 93

Brian T.A.
Brian T.A.

Reputation: 346

This function should return an array of ALL the keys (i.e. the key names) in a JSON object including nested key/value pairs.

function get_all_json_keys(json_object, ret_array = []) {
    for (json_key in json_object) {
        if (typeof(json_object[json_key]) === 'object' && !Array.isArray(json_object[json_key])) {
            ret_array.push(json_key);
            get_all_json_keys(json_object[json_key], ret_array);
        } else if (Array.isArray(json_object[json_key])) {
            ret_array.push(json_key);
            first_element = json_object[json_key][0];
            if (typeof(first_element) === 'object') {
                get_all_json_keys(first_element, ret_array);
            }
        } else {
            ret_array.push(json_key);
        }
    }

    return ret_array
}

Using this function on the OP's original object

const op_object =
{
    "document":{
       "people":[
          {
             "name":[
                "Harry Potter"
             ],
             "age":[
                "18"
             ],
             "gender":[
                "Male"
             ]
          },
          {
             "name":[
                "hermione granger"
             ],
             "age":[
                "18"
             ],
             "gender":[
                "Female"
             ]
          }
       ]
    }
 }

var all_keys = [];

function get_all_json_keys(json_object, ret_array = []) {
    for (json_key in json_object) {
        if (typeof(json_object[json_key]) === 'object' && !Array.isArray(json_object[json_key])) {
            ret_array.push(json_key);
            get_all_json_keys(json_object[json_key], ret_array);
        } else if (Array.isArray(json_object[json_key])) {
            ret_array.push(json_key);
            first_element = json_object[json_key][0];
            if (typeof(first_element) === 'object') {
                get_all_json_keys(first_element, ret_array);
            }
        } else {
            ret_array.push(json_key);
        }
    }

    return ret_array
}

get_all_json_keys(op_object, all_keys);

console.log(all_keys);

should yield

[ 'document', 'people', 'name', 'age', 'gender' ]

Note: This will return a unique list of all key names.

Upvotes: 5

AllanRibas
AllanRibas

Reputation: 1144

We must "parse" our jsonObject

 console.log('{"key0":"value0", "key1":"value1"}'); 
    var jsonObject = JSON.parse('{"key0":"value0", "key1":"value1"}')
    Object.keys(jsonObject).forEach(key => { 
        console.log(jsonObject[key]); //values 
        console.log(key); //keys 
    })

Upvotes: 0

RICARDO VASQUEZ
RICARDO VASQUEZ

Reputation: 96

var jsonData = { Name: "Ricardo Vasquez", age: "46", Email: "[email protected]" };

for (x in jsonData) {   
  console.log(x +" => "+ jsonData[x]);  
  alert(x +" => "+  jsonData[x]);  
  }

Upvotes: 3

Tuucan
Tuucan

Reputation: 93

ES6 of the day here;

const json_getAllKeys = data => (
  data.reduce((keys, obj) => (
    keys.concat(Object.keys(obj).filter(key => (
      keys.indexOf(key) === -1))
    )
  ), [])
)

And yes it can be written in very long one line;

const json_getAllKeys = data => data.reduce((keys, obj) => keys.concat(Object.keys(obj).filter(key => keys.indexOf(key) === -1)), [])

EDIT: Returns all first order keys if the input is of type array of objects

Upvotes: 8

BatScream
BatScream

Reputation: 19700

var input = {"document":
  {"people":[
    {"name":["Harry Potter"],"age":["18"],"gender":["Male"]},
    {"name":["hermione granger"],"age":["18"],"gender":["Female"]},
  ]}
}

var keys = [];
for(var i = 0;i<input.document.people.length;i++)
{
    Object.keys(input.document.people[i]).forEach(function(key){
        if(keys.indexOf(key) == -1)
        {
            keys.push(key);
        }
    });
}
console.log(keys);

Upvotes: 18

Rahul G Nair
Rahul G Nair

Reputation: 1376

Try this

var s = {name: "raul", age: "22", gender: "Male"}
   var keys = [];
   for(var k in s) keys.push(k);

Here keys array will return your keys ["name", "age", "gender"]

Upvotes: 51

Related Questions