9

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.

abc123
  • 17,855
  • 7
  • 52
  • 82
Arihant
  • 3,847
  • 16
  • 55
  • 86
  • `var key = key1` in your code should be `var key = 'key1'`, otherwise you're going to check if `undefined in global_move_obj`. – zzzzBov Jun 27 '16 at 20:08

2 Answers2

18

Use the hasOwnProperty call:

if (!obj.hasOwnProperty(key)) {

}
DᴀʀᴛʜVᴀᴅᴇʀ
  • 7,681
  • 17
  • 73
  • 127
tymeJV
  • 103,943
  • 14
  • 161
  • 157
2

You can do it like:

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

}
fedeghe
  • 1,243
  • 13
  • 22