Convert a JavaScript array to an object

While working in a project, we often may have a JavaScript array, but we need an object of the same data for some purpose. So, in this article, I will let you know how can you convert a JavaScript array to an object with example JS coding.

The easiest way of converting an array into a usable object is to use the spread operator (…) before the array. Using this operator we can expand our array expression in places where zero or more array elements are expected.

See the JS code below:

var goods = ["bench", "table", "shoe", "chair", "bag"];
var goodsObj = { ...goods };
console.log(goodsObj); // {0: "bench", 1: "table", 2: "shoe", 3: "chair", 4: "bag"}

The above code has been successfully converted our array into an object. You can run it and see the result. You will see an object in the console which contains the same elements that was in your array.

The above technique doesn’t use widely. The widely used technique to create an object from an array is using the Object.assign() method. Well, this technique is also going to be simple and easy like we just have seen above.

The Object.assign() method can copy the values of one or more source objects to a target object. In our case, we are going to pass just a blank object as the target where our array elements will be inserted.

Now below is the alternative and widely used technique to convert our JavaScript array into an object using the Object.assign() method:

var arr = [32, 65, 13, 94, 73];
arrObj = Object.assign({}, arr); 
console.log(arrObj); // {0: 32, 1: 65, 2: 13, 3: 94, 4: 73}

Also, read:

So we have done the same task in two different ways. Please let me know which method you prefer to generate an object using your existing array to fulfill your requirement.

Leave a Reply