Reputation: 45
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:
What I have tried:
Unexpected token M in JSON at position 0SyntaxError: Unexpected token M in JSON at position 0
Upvotes: 0
Views: 862
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
Reputation: 121
in javaScript typeof array is object for check array you can use Array.isArray
sample:
Array.isArray(["M","N"]); // true
Upvotes: 1