sammiwei
sammiwei

Reputation: 3200

What is the opposite of ("key" in obj ) in javascript?

This might seem very easy, but here is my question,what is the opposite of

if('name' in obj)

Is it if(!'name' in obj) or if("name" not in obj) or something else?

Thanks!

Upvotes: 4

Views: 869

Answers (5)

KooiInc
KooiInc

Reputation: 122906

there are a few ways, like:

if (!('name' in obj))
if (Object.keys(obj).indexOf('name')<0)

Upvotes: 2

RobG
RobG

Reputation: 147383

You may want:

if (obj.hasOwnProperty(propName)) 

which checks for a property on the object itself. To include inherited properties, other answers using the in operator will do.

Upvotes: 0

Tikhon Jelvis
Tikhon Jelvis

Reputation: 68152

"name" in obj is just a boolean expression, just like a && b || c. You can negate it like any other expression: !("name" in obj).

Upvotes: 2

jfriend00
jfriend00

Reputation: 707308

It would be like this:

if (!('name' in obj)) {
    // 'name' not found in obj
}

Upvotes: 4

user578895
user578895

Reputation:

just wrap it in parens:

if( !( 'name' in obj ) ){

Upvotes: 13

Related Questions