Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

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

Solution 2:

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"]

Solution 3:

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);

Solution 4:

ES6 of the day here;

constjson_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;

constjson_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

Solution 5:

var jsonData = { Name: "Ricardo Vasquez", age: "46", Email: "Rickysoft@gmail.com" };

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

Post a Comment for "How To Get All Key In Json Object (javascript)"