How to convert JavaScript Array to an Object
Converting a JavaScript array to an object can be done in various ways depending on what kind of object you need. Here are a few common methods:
1. Converting an Array to an Object with Key-Value Pairs
If you have an array of key-value pairs, you can use Object.fromEntries()
to convert it into an object. For example:
const array = [
["name", "John"],
["age", 30],
];
const obj = Object.fromEntries(array);
console.log(obj); // { name: 'John', age: 30 }
2. Using reduce
to Convert an Array to an Object
If you want to convert an array into an object with custom key-value logic, you can use the reduce()
method:
const array = ["apple", "banana", "cherry"];
const obj = array.reduce((acc, item, index) => {
acc[index] = item;
return acc;
}, {});
console.log(obj); // { '0': 'apple', '1': 'banana', '2': 'cherry' }
3. Creating an Object with Array Values as Properties
If you want to use array values as properties of an object, you can do this:
const array = ["name", "age"];
const values = ["John", 30];
const obj = {};
array.forEach((key, index) => {
obj[key] = values[index];
});
console.log(obj); // { name: 'John', age: 30 }
4. Using forEach
to Populate an Object
If you have a more complex array and want to create an object from it, you can use forEach()
:
const array = ["a", "b", "c"];
const obj = {};
array.forEach((value, index) => {
obj[`key${index}`] = value;
});
console.log(obj); // { key0: 'a', key1: 'b', key2: 'c' }
5. Using Array.prototype.map
to Create Key-Value Pairs
If your array elements are objects and you want to map them to a new object, you can use map()
combined with reduce()
:
const array = [
{ id: 1, value: "apple" },
{ id: 2, value: "banana" },
{ id: 3, value: "cherry" },
];
const obj = array.reduce((acc, { id, value }) => {
acc[id] = value;
return acc;
}, {});
console.log(obj); // { '1': 'apple', '2': 'banana', '3': 'cherry' }
6. Using Object.assign
for Merging Arrays of Objects
If you have an array of objects and want to merge them into a single object, you can use Object.assign()
:
const array = [{ a: 1 }, { b: 2 }, { c: 3 }];
const obj = Object.assign({}, ...array);
console.log(obj); // { a: 1, b: 2, c: 3 }
Choose the method that best fits your use case!