How to convert an array to an object
Short answer
Object.fromEntries() builds an object from an array of key-value pairs:
const pairs = [['name', 'Anna'], ['age', 30]];
console.log(Object.fromEntries(pairs));Output:
{
"name": "Anna",
"age": 30
}An index by id
To quickly find objects by id, make an object where the key is the id:
const users = [
{ id: 7, name: 'Anna' },
{ id: 9, name: 'Oleg' },
];
const byId = Object.fromEntries(users.map((user) => [user.id, user]));
console.log(byId[9].name);Output:
OlegTwo arrays: keys and values
Pair the elements of two arrays by their index:
const keys = ['red', 'green', 'blue'];
const values = ['#f00', '#0f0', '#00f'];
const colors = Object.fromEntries(keys.map((key, i) => [key, values[i]]));
console.log(JSON.stringify(colors));Output:
{"red":"#f00","green":"#0f0","blue":"#00f"}Common mistake
The spread operator turns an array into an object with numeric keys, which is rarely what you need:
console.log(JSON.stringify({ ...['a', 'b'] }));Output:
{"0":"a","1":"b"}Functions used in this recipe
- Object.fromEntries — Creates an object from a list of key–value pairs.
- Array.prototype.reduce — Reduces an array to a single value.
- Array.prototype.map — Creates a new array by transforming every element.