Probably you are already familiar with objects in JavaScript. Accessing a key-value pair is a very simple task, but things get complicated if the object has several key-value pairs or even other types of data structures. That's when the methods keys(), values() and entries() comes in handy. You will learn how to use these methods in this topic, so let's get started.
The key method
As the name already suggests, this method will take all the keys of an object and return them in an array. For this the following syntax is used: Object.keys(objectName).
You may be wondering why we have to use the Object keyword. That is because objects do not support array's methods like map(), filter(), forEach(), etc. So what the Object is doing here is transforming these values into an array so that you can iterate over these values using the array's methods.
Let's create a simple object and discuss how you can use the keys() method.
let employee = {
'name': 'Bruce Reese',
'email': '[email protected]',
'company': 'Velit Pellentesque Institute'
};Now let's store the result of the key method in another variable and print it to see what the result would be.
const employeeKeys = Object.keys(employee);
console.log(employeeKeys) // [ 'name', 'email', 'company' ]As you can see, an array containing all keys of the employee object has been generated. Now you can iterate over these values using all the array's methods. Let's use the forEach() method to interact with this array.
employeeKeys.forEach((key) => console.log(key));
// name
// email
// companyYou can also use each of these keys to access the values of the employee object.
employeeKeys.forEach((key) => console.log(employee[key]));
// Bruce Reese
// [email protected]
// Velit Pellentesque InstituteYou can even override the value of some key based on a condition. For example, if you want to override the name of this employee's company, you can use an if statement to check if the key equals company.
employeeKeys.forEach(key => {
if (key === 'company') {
employee[key] = "Stiedemann Group";
}
});Now, if you print out the object, you will see that the company has changed.
console.log(employee);
/*
{
name: 'Bruce Reese',
email: '[email protected]',
company: 'Stiedemann Group'
}
*/The values method
This values() method is similar to the keys() method, but instead of returning all the keys of the specific object, it returns their values.
The syntax is the same, all you have to do is replace the keys() method with the values method: Object.values(objectName)
Let's take a look at a more specific example:
const employeeValues = Object.values(employee);
console.log(employeeValues);
// [ 'Bruce Reese', '[email protected]', 'Velit Pellentesque Institute' ]You can use forEach() the same way you used the keys.
employeeValues.forEach((value) => console.log(value));
// Bruce Reese
// [email protected]
// Velit Pellentesque InstituteBe aware that you can only access an object's indices by its key. If you try to access a key that does not exist on the object, the result will be undefined.
employeeValues.forEach((value) => console.log(employee[value]));
// undefined
// undefined
// undefinedThe entries method
The entries() method has the same syntax as the other two methods but works in a different way. It returns the key-value pair of each pair in an array. Let's see how this works in the code:
const employeeEntries = Object.entries(employee);
console.log(employeeEntries);
/*
[
[ 'name', 'Bruce Reese' ],
[ 'email', '[email protected]' ],
[ 'company', 'Velit Pellentesque Institute' ]
]
*/You can see that the employeeEntries variable is an array with 3 other arrays inside it. Each array is a key-value pair of the object. You can access each one by the index.
console.log(employeeEntries[0]); // [ 'name', 'Bruce Reese' ]
console.log(employeeEntries[1]); // [ 'email', '[email protected]' ]Now you can use the forEach() method to access each of them. Each parameter will be an array, so you can retrieve the key and the value by index. Remember that the keys will always be in the first position of the array.
employeeEntries.forEach((entries) => {
const key = entries[0];
const value = entries[1];
console.log(`Key: ${key}, Value: ${value}`);
});
// Key: name, Value: Bruce Reese
// Key: email, Value: [email protected]
// Key: company, Value: Velit Pellentesque InstituteConclusion
In this topic you've learned how to use the keys(), values() and entries() methods. These methods are essential when we want to work with the keys and values of objects. Now let's put all this into practice with some exercises.