Object.keys()

We can use a JSON property's key to access a property's value. In the example below, we access the value of the surname key.

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

console.log(employees["surname"]) // will output "Anglesey"

The Object.keys() method returns an array containing all of an object's property keys (from the key:value pair). The keys are stored in the array as a list of strings. The keys will be stored in the array in the same order that they occur in the JSON object.

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

console.log(Object.keys(employees)) // output will be ["forename", "surname", "role"]

 

The Object.keys() method can be used for validation. If a set of individual validation tests are stored in a JSON, then the Object.keys() method can be used to test if all the validation tests have been passed.

let validationTests = {name: true, address: false, age: true, phone: true}

let passedAllTests = Object.keys(validationTests).every(key =>validationTests[key])

document.write(`Output is `, passedAllTests)  // output is false

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

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

 
<div align="center"><a href="../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:0;color:white;background-color:white'>&nbsp;</a></div>