Convert Dictionary into an Array of objects in JavaScript
Last Updated :
04 Mar, 2024
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:
Using Object.keys() and map()
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.
Javascript
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' }
]
Using Object.entries()
JavaScript introduced the Object.entries() method with ECMAScript 2017 (ES8). This method returns an array of key and values of the operating object. This technique offers a clear alternative to using Object.keys() manually to complete a conversion.
Example: The below code will explain the use of object.entries() method to convert a dictionary into an array of objects.
Javascript
const dictionaryToArrayOfObjects = (dictionary) => {
return Object.entries(dictionary).
map(([key, value]) => ({ key, value }));
};
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' }
]
Using for/in loop
Alternatively, you can manually iterate through the entries of the dictionary using a for/in loop and construct an array of objects.
Example: The below code implements the for/in loop to convert a dictionary into an array of objects.
Javascript
const dictionaryToArrayOfObjects = (dictionary) => {
const result = [];
for (const key in dictionary) {
if (Object.prototype.
hasOwnProperty.call(dictionary, key)) {
result.push({ key, value: dictionary[key] });
}
}
return result;
};
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' }
]
Share your thoughts in the comments
Please Login to comment...