sac Dahal
sac Dahal

Reputation: 1241

sending an array of data through postman to node

Ok I want to send an array of data and fetch it based on its index.

rate = [10,20,30,40,50,60,70,80,90,100,110,120,200];

enter image description here

when I try

console.log(req.body.rate); // output : [10,20,30,40,50,60,70,80,90,100,110,120,200]
console.log(req.body.rate[2]) // gives 0 
 // Also tried
var array = [];
array = req.body.rate;
console.log(array[2]) // same as above

I know I can loop and push etc. But I don't want to loop. Can anyone help me where I am gooing wrong.

Upvotes: 0

Views: 1662

Answers (2)

Kenneth Voss
Kenneth Voss

Reputation: 49

Could you send an array of objects instead? Then you could do something like this:

var arr = [
    {
        "key": "value" 
    },
    {
        "key": "value1" 
    },
    {
        "key": "value2" 
    }
]

console.log(arr[1].key)

Upvotes: 1

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48427

It seems that in your case req.body.rate it returns a string not an array.

To obtain an array, use split method.

var array = [];
array = req.body.rate.split(',');
console.log(array[2]) 

Upvotes: 1

Related Questions