0

I need to create an array from JSON data in node.js. I dont want to use jquery selector for this.

data = { List : ['1' , '2' , '3'] }

I am sending this data in the ajax call (POST). At the server end receving is:-

reqArray = req.param('List');
reqArray contains:- ['1' ,'2' ,'3']

I need this reqArray as an input to $in in mongoDb ,where it takes array as as input.

In the format [1 ,2 , 3] please suggest a way of doing this.

Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
Raja
  • 305
  • 2
  • 4
  • 14

1 Answers1

0

Try using the map function:

var numberArray = reqArray.map(function(element) {
    return +element;
});

The + will automatically convert it to a number.

Like correctly commented it is even better to use:

var numberArray = reqArray.map(Number);
Amberlamps
  • 39,180
  • 5
  • 43
  • 53
  • 5
    Simpler: `['1','2','3'].map(Number); //=> [1,2,3]` – elclanrs Sep 26 '13 at 08:08
  • if its not a number , lets suppose some alphaNum , then how to do this ? – Raja Sep 26 '13 at 08:12
  • 1
    The real question is, how do you want to handle `NaN` values? – Amberlamps Sep 26 '13 at 08:14
  • actually its going to be an _id for mongodb collection... using an array of this _ids as in input to $in in finding all the list from the collection in one go. – Raja Sep 26 '13 at 08:22
  • Is an `_id` always an integer? If not, the whole question makes no sense. If it is, you need some error handling, when an element of the array is not a number. – Amberlamps Sep 26 '13 at 08:25