2

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!

2
  • What is creating the array like this in the first place? Commented Nov 27, 2013 at 15:51
  • @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. Commented Nov 27, 2013 at 16:05

2 Answers 2

2

you totally can use JSON.stringify

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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"]]]
...and yes this is a valid JSON for JSONLint (JSON validator).
1

There is no built-in method for the same.

You can use the following function:

//array
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.

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.