I have a simple program like:
var a = {'a': 1, 'b': 2}
console.log(a)
console.log(a instanceof Array)
console.log(a.constructor instanceof Array)
Here value of a
is dictionary. I want to check for it.
How can I check in javascript. My both test above gives me false value
I am new to javascript
The simplest approach to check if something is a dictionary in Javascript in a way that will not also return true when given an array is: if (a. constructor == Object) { // code here... } This was inspired by the answer here.
We can use Object. keys(myDict). length to get the size of the dictionary and check if it's empty ( === 0 ).
Using hasOwnProperty() function The function hasOwnProperty() will check for the existence of a key in the given object and returns true if the key is present or else it returns false. This function takes the key of the object as the parameter and returns the Boolean result accordingly.
The simplest approach to check if something is a dictionary in Javascript in a way that will not also return true
when given an array is:
if (a.constructor == Object) {
// code here...
}
This was inspired by the answer here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With