[Solved-5 Solutions] Check does an object has property in JavaScript - javascript tutorial



Problem:

How to check if an object has a property in JavaScript ?

Solution 1:

The hasOwnProperty() method returns a boolean whether the object has the specified property as its own property to be indicated.

const object2 = new Object();
object2.property2 = 25;

console.log(object2.hasOwnProperty('property2'));
// expected output: true

console.log(object2.hasOwnProperty('toString'));
// expected output: false

console.log(object2.hasOwnProperty('hasOwnProperty'));
// expected output: false
true
false
false

Solution 2:

You can use this 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 );
    }
}

Solution 3:

Use Underscore.js

  • _.has(x, 'key'); Which calls Object.prototype.hasOwnProperty, but
    • It is shorter to type
    • Uses "a safe reference to hasOwnProperty" (i.e. it works even if hasOwnProperty is overwritten).
   function has(object, key) {
      return object ? hasOwnProperty.call(object, key) : false;
   }
   // hasOwnProperty = Object.prototype.hasOwnProperty

Solution 4:

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

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.

(function (undefined) {
    … your code …
    if (x.attribute !== undefined)
        … mode code …
})();

Solution 5:

var x = {'key': 1};

if ('key' in x) {
    console.log('has');
}


Related Searches to Check does an object has property in JavaScript - javascript tutorial