Let’s get started!
Table of Contents
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" }
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
.
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" }
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