javascript - How to convert an array-like string to an array in Node.js? - Stack Overflow

I am writing an API in a Node.js application. This is a POST call that sends a bunch of data and along

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 ma-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?

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 ma-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?

Share Improve this question asked Sep 14, 2015 at 9:01 JackHJackH 4,7454 gold badges38 silver badges64 bronze badges 4
  • 3 How about JSON.parse? – Blakes Seven Commented Sep 14, 2015 at 9:02
  • 1 That worked! Thanks! Can you answer the question so I can mark it as an answer? – JackH 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./questions/7545641/… – giri-sh 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 mon 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 Commented Sep 14, 2015 at 9:10
Add a ment  | 

1 Answer 1

Reset to default 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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745250608a4618657.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信