Last active
February 25, 2016 00:32
-
-
Save catichenor/8a4f58ce3f5b40ca329a to your computer and use it in GitHub Desktop.
Turns an standard Javascript array into a JSON object array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
exampleArray = [ "Hello", "World", "foo", "bar", "generic", "example", "recuerdos", "a todos" ]; | |
objText = ""; | |
for (i = 0, len = exampleArray.length; i < len; i++) { | |
thisResult = exampleArray[i]; | |
objText += '"obj_' + i + '": "' + thisResult + '", '; // First time this loops will result in --"obj_0": "Hello", -- | |
} | |
// objText should now be --"obj_0": "Hello", "obj_1": "World", "obj_2": "foo", "obj_3": "bar", -- etc., but this string ends with a comma, which JSON.parse won't allow. | |
parseableObject = objText.replace(/(.*), /, "{ $1 }"); // Removes the trailing comma and encloses in curly braces. | |
parsedObject = JSON.parse(parseableObject); // Now the array has been turned into an object. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment