JavaScript converts arrays into objects (JS arrays are often used to convert objects)
I want to get an array of elements and convert them into an object. The elements in the array need to be the keys of the object, with some default empty strings as values to be changed later.
['name','age','city', 'town', 'country'] { name: "", age: "", city: "", town: "", country: "" }
Finally I found that we can use the reduce method of the array.
We can create an empty object, pass array items and use them to create object keys dynamically.
const userChoices = ['name','age','city', 'town', 'country']; const result = ((acc, curr) => { acc[curr] = "" return acc }, {}) = "calvin" (result)
An empty object is used as an accumulator which is passed back to the function and fills the next item in the array.
acc is what we are trying to fill and return, while curr is the current item we are iterating over.
JSON object string to array in js
Given a JSON string, the task is to convert the JSON string to an array of JSON objects.
This array contains the values of JavaScript objects obtained from JSON strings with the help of JavaScript. There are two ways to solve this problem:
Method 1
First use the JSON.parse() method to convert the JSON string to a JavaScript object, then use the push() method to take out the values of the objects and push them into the array.
<!DOCTYPE HTML> <html> <head> <title> How to convert JSON string to array of JSON objects using JavaScript? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP"></p> <button onclick = "myGFG()"> Click Here </button> <p id = "GFG_DOWN"></p> <script> var up = ("GFG_UP"); var JS_Obj = '{"prop_1":"val_1", "prop_2":"val_2", "prop_3" : "val_3"}'; = "JSON string - '" + JS_Obj + "'"; var down = ("GFG_DOWN"); function myGFG() { var obj = (JS_Obj); var res = []; for(var i in obj) (obj[i]); = "Array of values - [" + res + "]"; } </script> </body> </html>
Method 2
This method is also similar, except that different methods are used. Use the eval() method to convert the JSON string to a JavaScript object, then take out the values of the objects and push them into the array using the push() method.
<!DOCTYPE HTML> <html> <head> <title> How to convert JSON string to array of JSON objects using JavaScript? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP"></p> <button onclick = "myGFG()"> Click Here </button> <p id = "GFG_DOWN"></p> <script> var up = ("GFG_UP"); var JS_Obj = '{"prop_1":"val_1", "prop_2":"val_2", "prop_3" : "val_3"}'; = "JSON string - '" + JS_Obj + "'"; var down = ("GFG_DOWN"); function myGFG() { var obj = eval('(' + JS_Obj + ')'); var res = []; for(var i in obj) (obj[i]); = "Array of values - [" + res + "]"; } </script> </body> </html>
For more information about JavaScript array to object and JSON object string to array, please see the following related links