How to Convert Array to object in Javascript

In this tutorial you can learn of how to convert array to object in javascript. you can understand a topic of convert array to json object in javaScript. This article will give you easy example of how to convert array to object in javascript example. you can easily convert array to object in javascript.

let’s see easy example that will help you.

1. Convert array to object in javascript using Object.assign() method

We will use Object.assign() for converting array to object using javascript. just pass object argument in Object.assign(). i will give simple example how to convert array into object in jQuery.

Example:
var arrayValue = [
    'first',
    'second',
    'third',
    'fourth',
    'fifth'
];

var objectValue = Object.assign({},array);

console.log(objectValue);
2. Convert array to object using reduce() method

This method iterate over the array, convert array value to object.let’see below example.

var arrayValue = ['a1', 'b1', 'c1'];
var objectValue = arrayValue.reduce((ass, currentValue1, index1) => {
    ass[index1] = currentValue1;
    return ass;
}, {});

console.log(objectValue);
3. Convert array to object using Array forEach() method

This method through the array and assign each element to the object with an index as the key.

var arrayValue = ['x1', 'y2', 'z3'];
var objectValue = {};
arrayValue.foreach((value1, index1) => {
   objectValue[index1] = value1; 
});

console.log(objectValue);

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *