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.

1

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

5 Comments

Simpler: ['1','2','3'].map(Number); //=> [1,2,3]
if its not a number , lets suppose some alphaNum , then how to do this ?
The real question is, how do you want to handle NaN values?
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.
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.

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.