3 Ways to Convert an Array to an Object in NodeJS

Let’s get started!

Table of Contents

  1. Object.assign()
  2. Loop Over Array & Construct a New Object
  3. Reduce()

1. 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.

 const array = ["Johnny", "Billy", "Sandy"]

const newObject = Object.assign({}, array)

// newObject = { "0": "Johnny", "1": "Billy", "2": "Sandy" }

2. 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.

3. Reduce()

The last example is the reduce() method. Reduce() method 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" }

Conclusion

Did we miss a method you use? Let us know in the comments.

Thanks for reading and happy coding!

If you liked this post, share it with all of your programming buddies!

Originally published by Nick Major at https://coderrocketfuel.com

#node-js #arrays

3 Ways to Convert an Array to an Object in NodeJS
27.55 GEEK