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