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?

4
  • 3
    How about JSON.parse? Commented Sep 14, 2015 at 9:02
  • 1
    That worked! Thanks! Can you answer the question so I can mark it as an answer? Commented Sep 14, 2015 at 9:06
  • When you assign it to a two dimensional array variable you can get the values of each value in it. does this help? - stackoverflow.com/questions/7545641/… Commented Sep 14, 2015 at 9: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. Commented Sep 14, 2015 at 9:10

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.