Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer

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);
share|improve this answer
5  
Simpler: ['1','2','3'].map(Number); //=> [1,2,3] –  elclanrs Sep 26 '13 at 8:08
 
@elclanrs: Thanks! –  Amberlamps Sep 26 '13 at 8:10
 
if its not a number , lets suppose some alphaNum , then how to do this ? –  Raja Sep 26 '13 at 8:12
1  
The real question is, how do you want to handle NaN values? –  Amberlamps Sep 26 '13 at 8: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 8:22
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.