Michael
Michael

Reputation: 13626

How can I check if variable property named id?

I have variable named t.

Some times this variable equal to some object:

var t = {id:2 Name:"Mike" };

And some times this variable might contain only string.Like this:

 var t = "someString";

At some point I need to check if variable is object and if it contains property named id.

How can I check if variable is object and contains property named id?

Upvotes: 1

Views: 72

Answers (3)

0xdw
0xdw

Reputation: 3842

You can check your variable using toString.call(value) === '[object Object]' and toString.call(value) === '[object String]'

var t = {
  id: 2,
  Name: "Mike"
};

function isObject(value, property) {
  return value !== null && toString.call(value) === '[object Object]' && value.hasOwnProperty(property);
}

function isString(value) {
  return value !== null && toString.call(value) === '[object String]';
}

document.write("isObject : " + isObject(t, 'id') + " | " + "isString : " + isString(t) + "<br>");

var t = "blabla";

document.write("isObject : " + isObject(t, 'id') + " | " + "isString : " + isString(t));

Upvotes: 1

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

You can use the && (and) operator

if (t && t.id && td.id === "blah")

Or shorter:

if (t && t.id === "blah")

Upvotes: 4

Tarun Dugar
Tarun Dugar

Reputation: 8971

Use typeof and hasOwnProperty:

if(typeof t == 'object' && t.hasOwnProperty('id')) {
     //your code for using t.id
}

Upvotes: 3

Related Questions