How to Check If an Object Has a Specific Property in JavaScript

How do I check if an object has a specific property in JavaScript?

2022 UPDATE

Object.hasOwn()

Object.hasOwn() is recommended over Object.hasOwnProperty() because it works for objects created using Object.create(null) and with objects that have overridden the inherited hasOwnProperty() method. While it is possible to workaround these problems by calling Object.prototype.hasOwnProperty() on an external object, Object.hasOwn() is more intuitive.

Example

const object1 = {
prop: 'exists'
};

console.log(Object.hasOwn(object1, 'prop'));
// expected output: true


Original answer

I'm really confused by the answers that have been given - most of them are just outright incorrect. Of course you can have object properties that have undefined, null, or false values. So simply reducing the property check to typeof this[property] or, even worse, x.key will give you completely misleading results.

It depends on what you're looking for. If you want to know if an object physically contains a property (and it is not coming from somewhere up on the prototype chain) then object.hasOwnProperty is the way to go. All modern browsers support it. (It was missing in older versions of Safari - 2.0.1 and older - but those versions of the browser are rarely used any more.)

If what you're looking for is if an object has a property on it that is iterable (when you iterate over the properties of the object, it will appear) then doing: prop in object will give you your desired effect.

Since using hasOwnProperty is probably what you want, and considering that you may want a fallback method, I present to you the following solution:

var obj = {
a: undefined,
b: null,
c: false
};

// a, b, c all found
for ( var prop in obj ) {
document.writeln( "Object1: " + prop );
}

function Class(){
this.a = undefined;
this.b = null;
this.c = false;
}

Class.prototype = {
a: undefined,
b: true,
c: true,
d: true,
e: true
};

var obj2 = new Class();

// a, b, c, d, e found
for ( var prop in obj2 ) {
document.writeln( "Object2: " + prop );
}

function hasOwnProperty(obj, prop) {
var proto = obj.__proto__ || obj.constructor.prototype;
return (prop in obj) &&
(!(prop in proto) || proto[prop] !== obj[prop]);
}

if ( Object.prototype.hasOwnProperty ) {
var hasOwnProperty = function(obj, prop) {
return obj.hasOwnProperty(prop);
}
}

// a, b, c found in modern browsers
// b, c found in Safari 2.0.1 and older
for ( var prop in obj2 ) {
if ( hasOwnProperty(obj2, prop) ) {
document.writeln( "Object2 w/ hasOwn: " + prop );
}
}

The above is a working, cross-browser, solution to hasOwnProperty(), with one caveat: It is unable to distinguish between cases where an identical property is on the prototype and on the instance - it just assumes that it's coming from the prototype. You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful.

javascript: best way of checking if object has a certain element or property?

Let's check the reliability of these ways of checking if object has a certain element or property:

This can fail if Boolean(person.age) is false

if (person.age) { ... }

This can fail if person.age is null or undefined

if (person.age != undefined) { ... }

These can fail if person.age is undefined

if (person.age !== undefined) { ... }
if (typeof(person.age) != 'undefined') { ... }

On the other hand, the hasOwnProperty() method returns a boolean indicating whether the object has the specified property as own (not inherited) property. So It does not depend on the value of person.age property. So it is the best way here

if (person.hasOwnProperty('age')) { ... }

If you want to go further and check if an object has a property on it that is iterable(all properties including own properties as well as the inherited ones) then using for..in loop will give you the desired result.

How to check if an object has certain properties

You can compare the two object's (recursive) key sets.

const
myObjA = {
name: "somebody",
class: { number: 9, section: "C" },
address: { house: 22, street: "Eg street", PIN: 7893 }
},
myObjB = {
name: "somebody else",
class: { number: 1, section: "A" },
address: { house: 11, street: "Another st", PIN: 0000 }
};

// Adapted from: https://stackoverflow.com/a/53620876/1762224
const gatherKeys = obj => {
const
isObject = val => typeof val === 'object' && !Array.isArray(val),
addDelimiter = (a, b) => a ? `${a}.${b}` : b,
paths = (obj = {}, head = '') => Object.entries(obj)
.reduce((product, [key, value]) =>
(fullPath => isObject(value)
? product.concat(paths(value, fullPath))
: product.concat(fullPath))
(addDelimiter(head, key)), []);
return new Set(paths(obj));
};

const
diff = (a, b) => new Set(Array.from(a).filter(item => !b.has(item))),
equalByKeys = (a, b) => diff(gatherKeys(a), gatherKeys(b)).size === 0;

console.log(equalByKeys(myObjA, myObjB));
.as-console-wrapper { top: 0; max-height: 100% !important; }

How to check if object has any properties in JavaScript?

You can loop over the properties of your object as follows:

for(var prop in ad) {
if (ad.hasOwnProperty(prop)) {
// handle prop as required
}
}

It is important to use the hasOwnProperty() method, to determine whether the object has the specified property as a direct property, and not inherited from the object's prototype chain.

Edit

From the comments: You can put that code in a function, and make it return false as soon as it reaches the part where there is the comment

How do I check if an object has only one property or only two properties and no other property in javascript

Object.keys(obj1).length == 1 && obj1.a

and

Object.keys(obj2).length == 2 && obj2.a && obj2.b

both utilize the number of keys.

Checking if object has property with given name returns false

You have three objects and the methods you are using to test are meant for a single object.

  • obj - object containing a games property
  • obj.games - array with one element
  • obj.games[0] - object with id property

Consider these which all are true:

let obj = {
games: [
{id: 'test'}
]
}

console.log(`obj.hasOwnProperty('games')`, obj.hasOwnProperty('games'))
console.log(`'games' in obj`, 'games' in obj)

console.log(`obj.games.hasOwnProperty('0')`, obj.games.hasOwnProperty('0'))
console.log(`'0' in obj.games`, '0' in obj.games)

console.log(`obj.games[0].hasOwnProperty('id')`, obj.games[0].hasOwnProperty('id'))
console.log(`'id' in obj.games[0]`, 'id' in obj.games[0])

if (obj && obj.games && obj.games.length > 0 && obj.games[0].id) {
console.log('obj.games has at least one element, '
+ 'and the first element has an id')
}

let id = obj && obj.games && obj.games.length > 0 && obj.games[0].id;
console.log('id:', id);



Related Topics



Leave a reply



Submit