Suklesh Rao
Suklesh Rao

Reputation: 45

Returned value is an object and not an array, Node.js and Postman

So I am trying a very simple query like shown below on Postman:

JSON input for Postman

 {
        "id" : ["M","N"]
}

I want to get back multiple ids from the Cosmos DB Server so I am using an array with many ids.

Now this is the start of my API where I am getting the data from the user:

let c_id: any = req.body.id;
console.log(c_id)
console.log(typeof(c_id))

//let c_id1 = JSON.parse(c_id)
//console.log(c_id1)
//console.log(typeof(c_id1))

Now what I expect to get back from Postman is the array, but I keep getting back an object.

What confuses me even more is that the console.log(c_id) statement prints this out as an object

console.log output

[ 'M', 'N' ]      //console.log(c_id) output
object           //console.log(typeof(c_id)) output

I do not understand what exactly is happening here. How can get the data back as an array?

Steps to replicate the problem:

  1. Just create a POST request on Postman with a key, value pair where an array is the value
  2. Create a request for id in your API and console log the output

What I have tried:

  1. Since it was giving me back an object, I tried parsing it but got back an error.

Unexpected token M in JSON at position 0SyntaxError: Unexpected token M in JSON at position 0

  1. I tried using just as an array, but I was not getting the expected output.

Upvotes: 0

Views: 862

Answers (2)

Maxim  Dmitrachkov
Maxim Dmitrachkov

Reputation: 56

That works as it should be. Array is object. You can even try it in your browser's console:

const a  = [1,2,3];
console.log(typeof(a));

or just:

console.log(typeof([1,2,3]));

those will produce the same result in console which is 'object'

Check out how operator typeof works. Since an array and other non-primitives (Maps, Sets, Date objects, RegExps) inherit from an Object class, the typeof operator is producing correct result in your case.

If you need to check whether an array you're getting or not, you can check you object for having methods or properties which belong only for needed object kind such as:

typeof([].length) == 'number'

Upvotes: 1

MAjidH1
MAjidH1

Reputation: 121

in javaScript typeof array is object for check array you can use Array.isArray

sample:

Array.isArray(["M","N"]);  // true

Upvotes: 1

Related Questions