This tutorial will illustrate the ways to convert JSON to an array and map in JavaScript.
How to Convert JSON to JavaScript Array?
To convert JSON to an array, use the “JSON.parse()” method. This method is used for converting the JSON string to an object. For converting the JSON string to an array, we will first convert the string to an object and then call the “push()” method for adding values in an empty array.
Syntax
Use the following method for the “JSON.parse()” method:
It accepts a JSON string as an input and gives an object as an output.
Example
Create a JSON string named “strJSON ”:
Invoke the “JSON.parse()” method by passing the JSON string as an argument that converts it into an object:
Create an empty array named “arrayJSON”:
Iterate the converted object called “objJSON” and push the values against each key to the array using the “push()” method:
arrayJSON.push(objJSON[i]);
}
Finally, print the array on the console:
It can be seen that the JSON has been successfully converted to an array:
How to Convert JSON to map in JavaScript?
For converting JSON to map, use the “Map()” constructor with the “Object.entries()” and “JSON.parse()” methods. The “JSON.parse()” method converts the string into an object, while the “Object.entries()” method gives an array of key-value pairs from the converted object. The “Map” constructor creates a new Map object from the array of entries.
Syntax
Use the given syntax for converting JSON to map in JavaScript:
Example
Call the “Map()” constructor with “Object.entries()” and “JSON.parse()” method by passing the JSON string as an argument:
Print the map on the console using “console.log()” method:
Output
We have provided all the necessary information related to the conversion of JSON to array/map in JavaScript.
Conclusion
For converting JSON to an array, use the “JSON.parse()” method with the “push()” method, and to convert JSON to a map, utilize the “Map()” constructor with the “Object.entries()” and “JSON.parse()” method. JSON.parse() method is the key method for conversion as it converts the JSON string to an object. This tutorial illustrated the methods to convert JSON to an array and map in JavaScript.