4

I am writing an API in a Node.js application. This is a POST call that sends a bunch of data and along with it, it sends the timings parameter in the body as a string that looks like an array [["11:00 AM", "1:00 PM"], ["1:00 PM", "4:00 PM"]]. When I am inserting it into MongoDB, it is getting stored as an array but with the entire text as a string in the first array element.

I know I can circumvent this by asking the client application to send a comma-separated string like 11:00 AM,1:00 PM and split the string in JavaScript before inserting it into the database using String.split() but that only works for single-dimension arrays. I have a multi-dimensional array that is being sent as a string in the POST request. How do I convert it to an array?

JackH
  • 4,613
  • 4
  • 36
  • 61
  • 3
    How about `JSON.parse`? – Blakes Seven Sep 14 '15 at 09:02
  • 1
    That worked! Thanks! Can you answer the question so I can mark it as an answer? – JackH Sep 14 '15 at 09:06
  • When you assign it to a two dimensional array variable you can get the values of each value in it. does this help? - http://stackoverflow.com/questions/7545641/javascript-multidimensional-array – giri-sh Sep 14 '15 at 09:08
  • If you are building web servers in JavaScript then search for the term "body parser", as it is a pretty common case to just convert string input that is acutally a `JSON` or other serialized format into a real data structure. And the work is generally handled for you. – Blakes Seven Sep 14 '15 at 09:10

1 Answers1

6

Use JSON.parse to parse string array to JS array.

var timingsAr = '[["11:00 AM", "1:00 PM"], ["1:00 PM", "4:00 PM"]]'
JSON.parse(timingsAr); //returns JS array
venkat7668
  • 2,657
  • 1
  • 22
  • 26