Converting an Array of Objects to an Object
In this post we will see the different ways to converting an Array to an Object. Below list are some of the ways that I have encountered during my programming career.
- for loop
- ES6
reduce()
method Object.fromEntries
Object.assign
- Underscore and Lodash
See this post also Convert an Object to an Array in JavaScript
let we know about Object, it is something that has key and value pairs(separated by colon).
var person = { firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue" };
for loop
Simply we can iterate over the array and assign the key value pairs to the Object.
var arr = [{ key: "Name", value: "Pritha" }, { key: "Age", value: "25" }]; var result = {}; for (var i=0, len=arr.length; i < len; i++) { result[arr[i].key] = arr[i].value; } console.log(result) // {Name: "Pritha", Age: "25"}
ES6 reduce() method
This is one of the popular way to convert array into an object. If the array is empty then it will return the empty object.
var arr = [{ key: "Name", value: "Potter" }, { key: "Age", value: "25" }]; function arrayToObject(pairs) { return pairs.reduce((obj, item) => (obj[item.key] = item.value, obj) ,{}); }; console.log(arrayToObject(arr)); // {Name: "Potter", Age: "25"}
Last {}
is the initial obj
value for reduce function, if you won’t provide the initial value the first arr
element will be used (which is probably undesirable).
Object.fromEntries
It is quite new method which convert the Object to an Array introduced in 2019. Make sure you only pass a key-value pair.
var arr = [{ key: "Name", value: "Helen" }, { key: "Age", value: "25" }]; console.log(Object.fromEntries(arr.map(item => [item.key, item.value]))); //{Name: "Helen", Age: "25"}
Object.assign
var arr = [{ key: "Name", value: "Gim" }, { key: "Age", value: "25" }]; console.log(Object.assign({}, ...arr.map(item => ({ [item.key]: item.value })))); //{Name: "Gim", Age: "25"}
Underscore and Lodash
const array = [ ['Name', 'Sugumar'], ['Age', '25'], ]; //Lodash _.fromPairs(array); //Underscore _.object(array); //Output: {Name: "Sugumar", Age: "25"}
Browser Support
Except for Internet Explorer, most major browsers have support for this method.