How to Create Array of Objects From Keys & Values of Another Object in JavaScript ?
Last Updated :
30 Jan, 2024
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.
Below approaches can be used to accomplish this task
In this approach, we are using Object.keys() and reduce() method to create an array of objects from the keys and values of an object. It iterates over keys, pushing objects into an accumulator array with key-value pairs, resulting in the desired array.
Syntax:
Object.keys(obj);
array.reduce( function(total, currentValue, currentIndex, arr),
initialArray)
Example: The below code uses Object.keys() and reduce() methods to create array of objects from keys and values of another object.
Javascript
const myObject =
{
key1: 'HTML' ,
key2: 'CSS' ,
key3: 'JavaScript'
};
const arrayOfObjects =
Object.keys(myObject).reduce((acc, key) =>
{
acc.push({ [key]: myObject[key] });
return acc;
}, []);
console.log(arrayOfObjects);
|
Output
[ { key1: 'HTML' }, { key2: 'CSS' }, { key3: 'JavaScript' } ]
The Array.from() method can be used with Object.entries() to convert an object’s key-value pairs into an iterable array. The map() method transforms each entry into an object, creating an array of objects representing the original object’s keys and values.
Syntax:
Array.from(Object.entries(obj)).map();
Example: The below code uses above-discussed methods to create an array of objects from another object.
Javascript
const myObject =
{
key1: 'HTML' ,
key2: 'CSS' ,
key3: 'JavaScript'
};
const arrayOfObjects =
Array.from(Object.entries(myObject)).
map(([key, value]) => ({ [key]: value }));
console.log(arrayOfObjects);
|
Output
[ { key1: 'HTML' }, { key2: 'CSS' }, { key3: '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.
Javascript
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' } ]
Share your thoughts in the comments
Please Login to comment...