How to use Object.keys() and map() In Javascript
One popular method for converting a dictionary into an array of objects is to map the dictionary keys using the map method into an array of objects by first extracting them using Object.keys().
Example: The below code will explain the use of the object.keys() and map() methods to convert a dictionary into an array of objects.
const dictionaryToArrayOfObjects = (dictionary) => {
return Object.keys(dictionary).map(key => ({
key: key,
value: dictionary[key]
}));
};
const myDictionary = {
name: "John",
age: 30,
city: "New York"
};
const arrayOfObjects =
dictionaryToArrayOfObjects(myDictionary);
console.log(arrayOfObjects);
Output
[ { key: 'name', value: 'John' }, { key: 'age', value: 30 }, { 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()
Contact Us