Convert an array to a JSON in JavaScript
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.
|
1 2 3 4 5 6 7 8 |
var arr = [ 'x', 'y', 'z' ]; var json = { ...arr }; console.log(json); /* Output: { '0': 'x', '1': 'y', '2': 'z' } */ |
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.
|
1 2 3 4 5 6 7 8 |
var arr = [ 'x', 'y', 'z' ]; var json = Object.assign({}, arr); console.log(json); /* Output: { '0': 'x', '1': 'y', '2': 'z' } */ |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var arr = [ 'x', 'y', 'z' ]; const callbackfn = (json, value, index) => { json[index] = value; return json; }; var json = arr.reduce(callbackfn, {}); console.log(json); /* Output: { '0': 'x', '1': 'y', '2': 'z' } */ |
4. Using Array.prototype.forEach() function
The forEach() method can be used to execute a function for each array element.
|
1 2 3 4 5 6 7 8 9 |
var arr = [ 'x', 'y', 'z' ]; var json = {}; arr.forEach((value, index) => json[index] = value); console.log(json); /* Output: { '0': 'x', '1': 'y', '2': 'z' } */ |
Alternatively, you can iterate over the array and construct a json object.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
var arr = [ 'x', 'y', 'z' ]; var json = {}; for (var i = 0 ; i < arr.length; i++) { json[i] = arr[i]; } console.log(json); /* Output: { '0': 'x', '1': 'y', '2': 'z' } */ |
That’s all about converting an array to a JSON in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)