Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript check if dictionary

Tags:

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

like image 203
varad Avatar asked Jul 11 '16 10:07

varad


People also ask

How do you check if an object is a dictionary in 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.

How check dictionary is empty or not in JavaScript?

We can use Object. keys(myDict). length to get the size of the dictionary and check if it's empty ( === 0 ).

How do you check if a key exists in an array JavaScript?

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.


1 Answers

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.

like image 196
Floyd Avatar answered Oct 04 '22 00:10

Floyd