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
19k7 gold badges55 silver badges84 bronze badges
asked Jun 27, 2016 at 19:59
1
  • var key = key1 in your code should be var key = 'key1', otherwise you're going to check if undefined in global_move_obj. Commented Jun 27, 2016 at 20:08

2 Answers 2

18

Use the hasOwnProperty call:

if (!obj.hasOwnProperty(key)) {
}
GʀᴜᴍᴘʏCᴀᴛ
9,07820 gold badges91 silver badges164 bronze badges
answered Jun 27, 2016 at 20:00
Sign up to request clarification or add additional context in comments.

Comments

2

You can do it like:

var key = 'key1';
if (!('key1' in obj)) {
 ....
} 
// or
if (!(key in obj)) {
}
answered Jun 27, 2016 at 20:02

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.