Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a key exists in an object in javascript [duplicate]

I have the following object literal:

{ 
  'key1': 
  { 
    id: 'rr323',
    d: undefined,
    x: 560,
    y: 150 
  },
  'key2': 
  { 
    id: 'rr231',
    d: undefined,
    x: 860,
    y: 90 
  } 
}

I want to implement an if statement such as below:

if(key DOES NOT exist in object){  
//perform certain function 
}

I tried the following:

var key = key1;
if(!(key in global_move_obj)){
 // function
}

But that always returns true value when it should return false.

like image 801
Arihant Avatar asked Jun 27 '16 19:06

Arihant


People also ask

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

There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.

Can JavaScript object have duplicate keys?

In JavaScript, an object consists of key-value pairs where keys are similar to indexes in an array and are unique. If one tries to add a duplicate key with a different value, then the previous value for that key is overwritten by the new value.

How do you check if a key exists in an array of objects 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.

How do you check if a value is present in an object in JavaScript?

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.


2 Answers

Use the hasOwnProperty call:

if (!obj.hasOwnProperty(key)) {

}
like image 140
tymeJV Avatar answered Nov 14 '22 14:11

tymeJV


You can do it like:

var key = 'key1';
if (!('key1' in obj)) {
    ....
} 
// or
if (!(key in obj)) {

}
like image 22
fedeghe Avatar answered Nov 14 '22 15:11

fedeghe