Here is a need to convert an array into a JSON_Object. To do so we are going to use a few of the most preferred techniques. First, we need to know a few methods.
1) Object.assign() method
This method copies the values of all properties owned by enumerables from source objects(one or more) to a target object.
Syntax:
Object.assign(target, ...sources)
Parameters:
- target: It specifies the target object.
- sources: It specifies the source object(s).
2)-JSON.stringify() method
Use of JSON is to exchange data to/from a web server. While sending data to web server, the data need to be string.
This method converts the javascript Object(array in this case) into JSON_string.
Syntax:
JSON.stringify(Javascript Object)
Parameters:
- Javascript Object: It specifies the JavaScript object.
Example 1:This example converts the JS array to JSON String using JSON.stringify() method.
<!DOCTYPE html> < html > < head > < title > JavaScript | Convert array to JSON. </ title > </ head > < body style = "text-align:center;" id = "body" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 16px;" > </ p > < button onclick = "gfg_Run()" > Convert </ button > < p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </ p > < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var array = [34, 24, 31, 48]; el_up.innerHTML = "Array = [" +array+"]";; function gfg_Run(){ el_down.innerHTML = "JSON_String = '"+JSON.stringify(array)+"'"; } </ script > </ body > </ html > |
Output:
-
Before clicking on the button:
-
After clicking on the button:
Example 2:This example converts the JS array to JSON Object using Object.assign() method.
<!DOCTYPE html> < html > < head > < title > JavaScript | Convert array to JSON. </ title > </ head > < body style = "text-align:center;" id = "body" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 16px;" > </ p > < button onclick = "gfg_Run()" > Convert </ button > < p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </ p > < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var array = [34, 24, 31, 48]; el_up.innerHTML = "Array = [" +array+"]";; function gfg_Run(){ el_down.innerHTML = "JSON Object = "+JSON.stringify(Object.assign({}, array)); } </ script > </ body > </ html > |
Output:
-
Before clicking on the button:
-
After clicking on the button: