How to use Object.keys() and map() methods In Javascript
The Object.keys() method can be used to create an array of all the keys available in the object, then the map() method can be used to iterate over them and store them into an array as objects.
Syntax:
// Object.keys()
Object.keys(obj);
//map()
map((element, index, array) => { /* … */ })
Example: The below code example illustrates the use of the Object.keys() and map() method to accomplish the task.
const myObject = {
key1: "HTML",
key2: "CSS",
key3: "JavaScript",
};
const arrayOfObjects = Object.keys(myObject).map(
(key) => ({ [key]: myObject[key] })
);
console.log(arrayOfObjects);
Output
[ { key1: 'HTML' }, { key2: 'CSS' }, { key3: 'JavaScript' } ]
How to Create Array of Objects From Keys & Values of Another Object in JavaScript ?
Creating an array of objects from the keys and values of another object involves transforming the key-value pairs of the original object into individual objects within an array. Each object in the array represents a key-value pair from the source object.