添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
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!

@Explosion Pills I'm iterating the BIG array and sending each sub array to Mongodb, this is only a sub-array with '0' as index. – Cris69 Nov 27, 2013 at 16:05

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.

this is the result of console.log(string_for_mongo); ["0",[["id",1],["country",0],["people",3],["name","WELLINGTON ALFRED"],["location","hill"],["filename","243245.PDF"]]] – Cris69 Nov 27, 2013 at 16:24 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.