gpullen
gpullen

Reputation: 1133

Mongodb javascript query

I am querying a mongo database using a javascript file. I have a for loop and I am adding to myArray using myArray.push(value).

My problem is when I run the script in Robomongo I get 2 outputs - the length of the array(which I don't want) and the print statements(I want).

Is there anyway to prevent the script from outputting the length of the array - is there another function I should be using other than .push???

Here is some of the script:

var myArray = [];
var result = jobData['result'];

for(var i = 0; i < result.length; i++){
    var collection = result[i].Tolerances;
    for(var j = 0; j < collection.length; j++){
        var cur = collection[j];
        myArray.push(cur);      // I do not want this value outputted
    }
}
for(var x = 0; x < myArray.length; x++){
    var value = myArray[x];
    print("Currency From: "+value.FromCurrency+";Currency To: "+value.ToCurrency+";Tolerance: "+value.TolerancePercentage+");
};

If there is more detail required just let me know.

Upvotes: 3

Views: 82

Answers (1)

chridam
chridam

Reputation: 103335

You can use JavaScript's reduce() and map() methods to construct the new array without logging the length of the new array. The following example demonstrates how to use these two methods in your case:

var jobData = {
    result: [
        { Tolerances: ["foo", "bar"] },
        { Tolerances: ["abc", "def"] },
        { Tolerances: ["123", "456"] }
    ]
};
var myArray = [];
var result = jobData['result'];  

var tolerances = result.map(function (r){
    return r.Tolerances;    
});

myArray = tolerances.reduce(function (a, b){
    return a.concat(b);
});

printjson(myArray);
// prints ["foo","bar","abc","def","123","456"]

Check the demo below.

var jobData = {
	result: [
		{ Tolerances: ["foo", "bar"] },
		{ Tolerances: ["abc", "def"] },
		{ Tolerances: ["123", "456"] }
	]
}
var myArray = [];
var result = jobData['result'];


var tolerances = result.map(function (r){
	return r.Tolerances;	
})

myArray = tolerances.reduce(function (a, b){
	return a.concat(b);
})

pre.innerHTML = "myArray: " + JSON.stringify(myArray, null, 4);
<pre id="pre"></pre>

Upvotes: 3

Related Questions