Greetings, developers! In this blogpost, we will convert an object’s values or keys into an array.
Using Object.values()
Object.values() allows us to extract the values of an object and neatly organize them into an array. Here’s a simple example:
const sourceObject = {
property1: 'value1',
property2: 'value2',
property3: 'value3',
};
const arrayFromValues = Object.values(sourceObject);
console.log(arrayFromValues);
// Output: ['value1', 'value2', 'value3']
The Object.values() method provides a concise and efficient way to obtain an array containing the values from our source object.
Using Object.keys()
This method focuses on extracting the keys of an object and presenting them in array form:
const anotherObject = {
key1: 'value1',
key2: 'value2',
key3: 'value3',
};
const arrayFromKeys = Object.keys(anotherObject);
console.log(arrayFromKeys);
// Output: ['key1', 'key2', 'key3']
Object.keys() simplifies the process of obtaining an array of keys from an object, making it a valuable tool for various scenarios.
Using Key-Value Pairs with Object.entries()
Our final method is Object.entries(). This powerhouse not only reveals the keys but also pairs them with their corresponding values:
const pairedObject = {
propertyA: 'Alpha',
propertyB: 'Beta',
propertyC: 'Gamma',
};
const arrayFromEntries = Object.entries(pairedObject);
console.log(arrayFromEntries);
// Output: [['propertyA', 'Alpha'], ['propertyB', 'Beta'], ['propertyC', 'Gamma']]
By utilizing Object.entries(), we can generate an array where each entry comprises a key-value pair, offering a comprehensive view of our object’s structure.
🧪Practice Coding Problem: Create a Conversion Function
In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.
Implement the convertObjectToArray function. It should take an object and a parameter (values or keys) and return the corresponding array.
JavaScriptfunction convertObjectToArray(obj, type) { // > > > 👉 Write code here 👈 < < < } // Testing the function const valuesArray = convertObjectToArray(sourceObject, 'values'); const keysArray = convertObjectToArray(anotherObject, 'keys'); console.log(valuesArray); // Output: ['value1', 'value2', 'value3'] console.log(keysArray); // Output: ['key1', 'key2', 'key3']
Please attempt before seeing the Answer:
function convertObjectToArray(obj, type) {
if (type === 'values') {
return Object.values(obj);
} else if (type === 'keys') {
return Object.keys(obj);
}
}
This demonstrates the practical application of methods in this blog, allowing you to choose between values and keys based on your specific needs.
Hopefully, understanding these techniques will help in your Javascript journey. Keep Converting and Manipulating Javascript Objects into your folds. Happy coding 🚀 !