This post will discuss how to convert an array to a JSON in JavaScript.

There are several ways to convert an array to a JSON in JavaScript:

1. Using Spread Operator

ES6 Spread syntax allows an array to be expanded where object literals are expected. The following example demonstrates this use of Spread syntax.

Download  Run Code

2. Using Object.assign() function

The Object.assign() method is used to copy properties from a source object to a target object. To convert an array to JSON, pass an array as the source object and an empty object as a target.

Download  Run Code

3. Using Array.prototype.reduce() function

The reduce() method is used to execute a callback function on each array element. The following code example shows how to transform an array to a JSON object with the reduce() method.

Download  Run Code

4. Using Array.prototype.forEach() function

The forEach() method can be used to execute a function for each array element.

Download  Run Code

 
Alternatively, you can iterate over the array and construct a json object.

Download  Run Code

That’s all about converting an array to a JSON in JavaScript.