To convert array to JSON object string JavaScript; Through this tutorial, i am going to show how to convert array to JSON object string in JavaScript.
Convert Array to JSON Object JavaScript
See the following for how to convert array to JSON object string and object to array in JavaScript; as shown below:
- Convert Array to JSON Object JavaScript
- JavaScript Convert Object to Array
- Convert two dimensional ( 2d ) arrays to JSON Object JavaScript
JavaScript Convert Array to JSON Object String
Using JavaScript JSON.stringify() to convert an array into a JSON formatted string in JavaScript; as shown below:
var array = [1, 2, 3, 4]; var arrayToString = JSON.stringify(Object.assign({}, array)); // convert array to string var stringToJsonObject = JSON.parse(arrayToString); // convert string to json object console.log(stringToJsonObject);
Here, i will explain to you about above used javaScript functions:
- 1.JSON.stringify() and Object.assign() method convert array to JSON string.
- 2.JSON.parse() method convert string to JSON object in javascript.
JavaScript Convert Object to Array
Here, i will take an example to convert object to array using javaScript.entries()
method from the Object
class; as shown below:
var object = { "first_name": "Test", "last_name": "Test", "email": "[email protected]" } var arr = Object.entries(object); console.log(arr);
Convert two dimensional ( 2d ) arrays to JSON Object JavaScript
Let, you have array two dimensional; as shown below:
var arr = [ ["Status", "Name", "Marks", "Position"], ["active", "Akash", 10.0, "Web Developer"], ["active", "Vikash", 10.0, "Front-end-dev"], ["deactive", "Manish", 10.0, "designer"], ["active", "Kapil", 10.0, "JavaScript developer"], ["active", "Manoj", 10.0, "Angular developer"], ];
Want to convert this two deminsional array to JSON Object in javaScript. As shown below:
//array. var arr = [ ["Status", "Name", "Marks", "Position"], ["active", "Akash", 10.0, "Web Developer"], ["active", "Vikash", 10.0, "Front-end-dev"], ["deactive", "Manish", 10.0, "designer"], ["active", "Kapil", 10.0, "JavaScript developer"], ["active", "Manoj", 10.0, "Angular developer"], ]; //javascript create JSON object from two dimensional Array function arrayToJSONObject (arr){ //header var keys = arr[0]; //vacate keys from main array var newArr = arr.slice(1, arr.length); var formatted = [], data = newArr, cols = keys, l = cols.length; for (var i=0; i<data.length; i++) { var d = data[i], o = {}; for (var j=0; j<l; j++) o[cols[j]] = d[j]; formatted.push(o); } return formatted; }
Be First to Comment