How to use Object.entries() In Javascript
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.
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' } ]
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