How to use Object.values() and map() In Javascript
This approach leverages the Object.values() method, which returns an array of a given object’s own enumerable property values, and the Object.keys() method to construct an array of objects. This method is particularly useful when you only care about the values and want to include the corresponding keys in the result.
Example: The below code demonstrates using Object.values() and Object.keys() to convert a dictionary into an array of objects.
const dictionaryToArrayOfObjects = (dictionary) => {
return Object.keys(dictionary).map((key, index) => ({
key: key,
value: Object.values(dictionary)[index]
}));
};
const myDictionary = {
name: "John",
age: 22,
city: "New York"
};
const arrayOfObjects = dictionaryToArrayOfObjects(myDictionary);
console.log(arrayOfObjects);
Output
[ { key: 'name', value: 'John' }, { key: 'age', value: 22 }, { key: 'city', value: 'New York' } ]
Convert Dictionary into an Array of objects in JavaScript
In JavaScript, dictionaries also known as objects are used to store key-value pairs. But sometimes you might need to convert this data into an array of objects so that you can handle or utilize particular parts more easily.
Below are the multiple ways of converting a Dictionary into an Array of objects in JavaScript:
Table of Content
- Using Object.keys() and map()
- Using Object.entries()
- Using for/in loop
- Using Object.values() and map()