Xalsar
Xalsar

Reputation: 83

How can I check if an object exists and has X property?

I am trying to check if an object exists and has X property.

First I try it like this:

let object = {
    foo: 1
}

console.log('foo' in object)
console.log(object.hasOwnProperty('foo'))
console.log(typeof(object.foo) !== undefined)

But I realized that if the object is undefined all of them return errors.

I know I can use:

let object = undefined

if (object) {
    console.log('foo' in object)
    console.log(object.hasOwnProperty('foo'))
    console.log(typeof (object.foo) !== undefined)
}

To check if an object exists and has X property, but I would like to know if I can resume all of this in one line. Something like:

typeof(object) !== undefined && ('foo' in object)

Upvotes: 0

Views: 63

Answers (3)

Saeed
Saeed

Reputation: 5488

these examples works fine:

let object = {
  foo: 1
};

if (object && object.hasOwnProperty('foo')) {
  console.log(object['foo']);
} else {
  console.log('object has no foo key');
}

let obj2 = {};

if (obj2 && obj2.hasOwnProperty('foo')) {
  console.log(obj2['foo']);
} else {
  console.log('obj2 has no foo key');
}

let obj3;

if (obj3 && obj3.hasOwnProperty('foo')) {
  console.log(obj2['foo']);
} else {
  console.log('obj3 has no foo key');
}

For this one I don't have any idea

if (obj3 && obj3.hasOwnProperty('foo')) {
  console.log(obj2['foo']);
} else {
  console.log('obj3 has no foo key');
}

Upvotes: 1

Saša Tomislav Mataić
Saša Tomislav Mataić

Reputation: 1636

Just use check for existence of the object first:

object && 'foo' in object

Upvotes: 1

Jerodev
Jerodev

Reputation: 33186

You can use it just like you were doing in your multi line example, by just testing object.

function testObject(object) 
{
  if (object && ('foo' in object)) {
    console.log(true);
  } else {
    console.log(false);
  }
}

testObject(undefined);
testObject({foo: 'bar'});

Upvotes: 2

Related Questions