admin管理员组文章数量:1416321
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?
-
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
1 Answer
Reset to default 6Use 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
本文标签: javascriptHow to convert an arraylike string to an array in NodejsStack Overflow
版权声明:本文标题:javascript - How to convert an array-like string to an array in Node.js? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745250607a2649802.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论