Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I'm getting a BIG multidimensional array after combining few simple arrays, now I need to convert it in a JSON string right before sending it to Mongodb. Here is the array structure:
[ '0',
[ [ 'id', 1 ],
[ 'country', 0 ],
[ 'people', 3 ],
[ 'name', 'WELLINGTON ALFRED' ],
[ 'location', 'hill' ],
[ 'filename', 243245.PDF]]]
What's the best practice to do it in Node.js?
Thank's in advance!
–
string_for_mongo = JSON.stringify(your_array)
but you also can use any of these drivers for mongodb
if you want to convert these arrays to object you can just use something like this
pairs = {}
for ( pair in your_array[1] ) { pairs[your_array[1][pair][0]] = your_array[1][pair][1] }
objekt = {}
objekt[your_array[0]] = pairs
I think there is no better solution than not to use such an arrays. Try to form data in objects from the beginning.
–
var arr = [
["Status", "Name", "Marks", "Position"],
["active", "Akash", 10.0, "Web Developer"],
["active", "Vikash", 10.0, "Front-end-dev"],
["deactive", "Manish", 10.0, "designer"],
["active", "Kapil", 10.0, "JavaScript developer"],
["active", "Manoj", 10.0, "Angular developer"],
//javascript create JSON object from two dimensional Array
function arrayToJSONObject (arr){
//header
var keys = arr[0];
//vacate keys from main array
var newArr = arr.slice(1, arr.length);
var formatted = [],
data = newArr,
cols = keys,
l = cols.length;
for (var i=0; i<data.length; i++) {
var d = data[i],
o = {};
for (var j=0; j<l; j++)
o[cols[j]] = d[j];
formatted.push(o);
return formatted;
Reference: Click Here
Note: This might not give the output required for the input given in the question. I've provided the type of input this will work in arr
.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.