3 Ways to Convert an Array to an Object in Node.js
Do you need to convert an array with values to an object? In this article, we'll cover the three ways you can go about doing this.
Let's get started!
Table of Contents
Object.assign()
Object.assign()
is the first method we'll cover. This method is used to copy values from one or more source objects to a target object.
Here's what the code looks like:
const array = ["Johnny", "Billy", "Sandy"]
const newObject = Object.assign({}, array)
// newObject = { "0": "Johnny", "1": "Billy", "2": "Sandy" }
Loop Over Array & Construct a New Object
In this method, we're going to loop over each item in your array and add each one as a new property in a new object.
Here's the full code:
const array = ["Johnny", "Billy", "Sandy"]
let newObject = {}
for (let i=0; i < array.length; i++) {
if (array[i] !== undefined) {
newObject[i] = array[i]
}
}
// newObject = { "0": "Johnny", "1": "Billy", "2": "Sandy" }
First, we declare an empty object called newObject
that will hold the properties we will move over from the array.
Then, we use a for
loop to iterate over each value in the array. If the value doesn't have an undefined
value, we add the value as a new property to the newObject
.
Reduce()
The last example is the reduce()
method. reduce()
executes a provided function for each value of the array and the return values are stored in an accumulator, which is an object in this case.
const array = ["Johnny", "Billy", "Sandy"]
const newObject = array.reduce(function(result, item, index) {
result[index] = item
return result
}, {})
// newObject = { "0": "Johnny", "1": "Billy", "2": "Sandy" }
In this article, we showed you three different methods to convert an array to an object using Node.js: the Object.assign()
function, looping over the array to construct a new object, and the reduce()
function.