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

How do I examine if an object has a details building in JavaScript?

Consider:

x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
    //Do this
}

Is that the most effective means to do it?

1701
2022-07-22 15:25:17
Source Share
Answers: 7

Let is punctured some complication below. First, allow is streamline by thinking hasOwnProperty currently exists ; this holds true of the substantial bulk of existing internet browsers in operation.

hasOwnProperty returns real if the feature name that is passed to it has actually been included in the object. It is totally independent of the real value appointed to it which might be specifically undefined.

Hence:

var o = {}
o.x = undefined

var a = o.hasOwnProperty('x')  // a is true
var b = o.x === undefined // b is also true

However:

var o = {}

var a = o.hasOwnProperty('x')  // a is now false
var b = o.x === undefined // b is still true

The trouble is what takes place when an object in the model chain has a feature with the value of undefined? hasOwnProperty will certainly be incorrect for it, therefore will certainly !== undefined. Yet, for..in will certainly still list it in the list.

The lower line exists is no cross - internet browser means (given that Internet Explorer does not reveal __prototype__) to establish that a details identifier has actually not been affixed to an object or anything in its model chain.

34
2022-07-24 03:38:14
Source

Yes it is I assume you can additionally do Object.prototype.hasOwnProperty.call(x, 'key') which needs to additionally function if x has actually a building called hasOwnProperty

But that examinations for very own buildings. If you intend to examine if it has a building that might additionally be inhered you can make use of typeof x.foo != 'undefined'.

21
2022-07-22 17:25:38
Source
if (x.key !== undefined)

Armin Ronacher appears to have currently beat me to it, but:

Object.prototype.hasOwnProperty = function(property) {
    return this[property] !== undefined;
};

x = {'key': 1};

if (x.hasOwnProperty('key')) {
    alert('have key!');
}

if (!x.hasOwnProperty('bar')) {
    alert('no bar!');
}

A more secure, yet slower remedy, as pointed out by Konrad Rudolph and also Armin Ronacher would certainly be:

Object.prototype.hasOwnProperty = function(property) {
    return typeof this[property] !== 'undefined';
};
70
2022-07-22 17:21:45
Source

ALRIGHT, it resembles I had the appropriate solution unless if you do not desire acquired properties:

if (x.hasOwnProperty('key'))

Here are a few other alternatives to include acquired properties:

if (x.key) // Quick and dirty, but it does the same thing as below.

if (x.key !== undefined)
15
2022-07-22 17:21:21
Source
if(x.hasOwnProperty("key")){
  // …
}

due to the fact that

if(x.key){
  // …
}

falls short if x.key is falsy (as an example, x.key === "").

19
2022-07-22 17:20:29
Source

I'm actually perplexed by the solutions that have actually been offered - a lot of them are simply outright wrong. Certainly you can have object buildings that have actually undefined, null, or incorrect values. So merely lowering the building check to typeof this[property] or, also worse, x.key will certainly offer you entirely deceptive outcomes.

It relies on what you are seeking. If you need to know if an object literally has a building (and also it is not originating from someplace up on the model chain) after that object.hasOwnProperty is the means to go. All modern-day internet browsers sustain it. (It was missing out on in older variations of Safari - 2.0.1 and also older - yet those variations of the browser are hardly ever made use of anymore.)

If what you are seeking is if an object has a building on it that is iterable (when you iterate over the buildings of the object, it will certainly show up) after that doing: prop in object will certainly offer you your wanted result.

Given that making use of hasOwnProperty is possibly what you desire, and also taking into consideration that you might desire a contingency method, I offer to you the adhering to 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 functioning, go across - browser, remedy to hasOwnProperty, with one caution: It is incapable to compare instances where a the same building gets on the model and also on the instance - it simply thinks that it is originating from the model. You can change it to be extra forgiving or rigorous, based upon your scenario, yet at least this need to be extra handy.

1558
2022-07-22 17:02:19
Source

Note: the following is nowadays largely obsolete thanks to strict mode, and hasOwnProperty. The correct solution is to use strict mode and to check for the presence of a property using obj.hasOwnProperty. This answer predates both these things, at least as widely implemented (yes, it is that old). Take the following as a historical note.


Bear in mind that undefined is (unfortunately) not a reserved word in JavaScript if you’re not using strict mode. Therefore, someone (someone else, obviously) could have the grand idea of redefining it, breaking your code.

A more robust method is therefore the following:

if (typeof(x.attribute) !== 'undefined')

On the flip side, this method is much more verbose and also slower. :-/

A common alternative is to ensure that undefined is actually undefined, e.g. by putting the code into a function which accepts an additional parameter, called undefined, that isn’t passed a value. To ensure that it’s not passed a value, you could just call it yourself immediately, e.g.:

(function (undefined) {
    … your code …
    if (x.attribute !== undefined)
        … mode code …
})();
150
2022-07-22 15:54:57
Source