How to Convert an Array to an Object with JavaScript
Introduction
Data structures in JavaScript are often very composable. This means that you can take a data structure and transform it into a different data structure relatively easy. This is helpful when you need to transform data into a format that is more useful for your application.
In this article, we'll be looking at how to convert an array to an object with JavaScript.
Why Convert Arrays to Objects?
Objects in JavaScript provide a structured way to store data with key-value pairs. This structure can be beneficial when we want to access data using specific keys, rather than relying on indices as we do with arrays. For instance, if we have a list of users with their respective properties, it's much more intuitive to access a user's age with user.age
than with user[3]
.
Using the Object.assign() Method
One of the most obvious ways to convert an array to an object is by using the Object.assign()
method. This method copies all enumerable own properties from one or more source objects to a target object and returns the target object.
Here's a simple example:
let array = ['apple', 'banana', 'cherry'];
let object = Object.assign({}, array);
console.log(object);
The output will be:
{ '0': 'apple', '1': 'banana', '2': 'cherry' }
As you can see, the Object.assign()
method took our array and transformed it into an object, where the indices of the array became the keys of the object.
Note: The Object.assign()
method does not deep copy properties of the input object. This means that if your array contains objects and you modify those after using Object.assign()
, the changes will be reflected in the new object as well.
Using the Array.reduce() Method
Another method for converting an array to an object is the Array.reduce()
method. This applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single output value.
Here's how you can use it:
let array = ['apple', 'banana', 'cherry'];
let object = array.reduce((obj, item, index) => {
obj[index] = item;
return obj;
}, {});
console.log(object);
The output will be the same as the previous example:
{ '0': 'apple', '1': 'banana', '2': 'cherry' }
In this example, we're using Array.reduce()
to create a new object (obj
), and for each item in the array, we're adding a new property to obj
with a key of the current index and a value of the current item.
The advantage of the Array.reduce()
method is that it gives us more flexibility. We can easily modify the code to use the array items as keys and the indices as values, or to transform the data in other ways.
Using the Spread Operator
One of the most elegant and modern (i.e. ES6) ways to convert an array to an object in JavaScript is by using the spread operator (...
). Introduced in ES6, the spread operator lets us expand iterable elements like arrays into individual elements.
Here's how you can use the spread operator to convert an array to an object:
const array = ['apple', 'banana', 'cherry'];
const object = { ...array };
console.log(object);
The output of the above code will be:
{ '0': 'apple', '1': 'banana', '2': 'cherry' }
As you can see, the array indices become the keys of the object, and the array elements become the corresponding values.
Converting Multidimensional Arrays
Dealing with multidimensional arrays can be a bit confusing, especially for novice programmers. Lucky for us, JavaScript provides us with some nice tools to handle them. Let's say we have a 2D array where each sub-array contains a pair of values. We can convert this to an object where the first element of each pair is the key and the second element is the value:
const array = [['name', 'John'], ['age', 30], ['city', 'New York']];
const object = Object.fromEntries(array);
console.log(object);
The output will then be:
{ name: 'John', age: 30, city: 'New York' }
The Object.fromEntries()
method transforms a list of key-value pairs into an object, which is perfect for our use case. The data in the multidimensional array is now much easier to access.
Converting Arrays with Non-numeric Indices
Note: JavaScript arrays are technically objects, where indices are properties that can be strings. However, when we talk about arrays in a conventional sense, we usually think of them as lists with numeric indices.
So, how do we convert an array with non-numeric indices to an object? Well, in JavaScript, it's already an object! But if we want to convert it into a more standard object format, we can use the Object.assign()
method.
Consider the following:
const array = [];
array['name'] = 'John';
array['age'] = 30;
array['city'] = 'New York';
const object = Object.assign({}, array);
console.log(object);
The output will be:
{ name: 'John', age: 30, city: 'New York' }
In case you're curious, what does the array
variable look like after assigning values to non-numeric indices? This can be pretty unintuitive, but once you can wrap your head around arrays actually being objects, it can make more sense.
const array = [];
array['name'] = 'John';
array['age'] = 30;
array['city'] = 'New York';
console.log(object);
[ name: 'John', age: 30, city: 'New York' ]
Conclusion
In this Byte, we've seen the different ways to convert an array to an object in JavaScript, including using Object.assign()
, Array.reduce()
, and the spread operator. We also showed how to deal with multidimensional arrays and handle arrays with non-numeric indices.