Object.keys()

The Object.keys() method can be applied to JSON objects.

If the JSON object is not in an array, then Object.keys() returns an array containing all of the object's property names (from the name:value pair). The property names are stored in the array as a list of strings. The property names are stored in the array in the same order that they occur in the JSON object.

let employee = {forename:"Ann", surname:"Anglesey", role:"IT"}

alert(Object.keys(employee)) // output will be Array ["forename", "surname", "role"]

We can use the array to access items in the JSON object. For example

let employee = {forename:"Ann", surname:"Anglesey", role:"IT"} 

console.log(Object.keys(employee).map(index => employee[index])) // output will be Array ["Ann", "Anglesey", "IT"]

Object.keys() can be used to perform validation. Given the JSON list {name:true, address:false, age:true, gender:true}, which contains a set of properties that are each set to true or false, write code to detect if at least one property has been set to "true", as shown here.

Given the JSON list {name:true, address:false, age:true, gender:true}, which contains a set of properties that are each set to true or false, write code to detect if all properties have been set to "true", as shown here.

If the JSON object contains a set of JSON objects within an array, then Object.keys() returns an array containing a set of indices, with one index representing each JSON object in the array of JSON objects.

let employees = [ {forename:"Ann", surname:"Anglesey", role:"IT"}, 
                  {forename:"Brian", surname:"Brown", role:"HR"}, 
                  {forename:"Cathy", surname:"Connolly",role:"HR"}, 
                  {forename:"Dennis", surname:"Deagan", role:"IT"}, 
                  {forename:"Emma", surname:"Epstein", role:"HR"} ] 

let indicesArray = Object.keys(employees)
alert(indicesArray) // will display 0,1,2,3,4
 
<div align="center"><a href="file:///C|/Users/Derek/Documents/Notes/versionC/index.html" title="DKIT Lecture notes homepage for Derek O&#39 Reilly, Dundalk Institute of Technology (DKIT), Dundalk, County Louth, Ireland. Copyright Derek O&#39 Reilly, DKIT." target="_parent" style='font-size:0color:whitebackground-color:white'>&nbsp;</a></div>