How to Check If Object Property Exists with a Variable Holding the Property Name

How to check if object property exists with a variable holding the property name?

var myProp = 'prop';
if(myObj.hasOwnProperty(myProp)){
alert("yes, i have that property");
}

Or

var myProp = 'prop';
if(myProp in myObj){
alert("yes, i have that property");
}

Or

if('prop' in myObj){
alert("yes, i have that property");
}

Note that hasOwnProperty doesn't check for inherited properties, whereas in does. For example 'constructor' in myObj is true, but myObj.hasOwnProperty('constructor') is not.

How would you check if property name(s) from one object exist in another?

(1) Look properties on an object by a variable property name by using bracket notation, not dot notation

(2) To check if something is undefined, either compare against undefined directly, or use typeof and compare against the string 'undefined' (but this check isn't needed for this algorithm)

(3) Make sure the properties are own properties, not inherited properties, with hasOwnProperty

let object1 = { a: 'string' } 
let object2 = { a: 1, b: 2, c: 3, d: 4 }

fillObj = function (object2, object1) {
for (let key in object1) {
if (object1.hasOwnProperty(key)) {
object2[key] = object1[key];
}
}
return object2; //should return {a: 'string', b: 2, c: 3, d: 4 }
};

console.log(fillObj(object2, object1));

How to dynamically check if a property exists in an object?

You're not properly optional chaining your errors?.logic[conditionIndex]?.scenarios[scenarioIndex]?.operator bit.

If you want to optional chain with a [key] access, use ?.[key], e.g. errors?.logic?.[conditionIndex]?.scenarios?.[scenarioIndex]?.operator.

Check object variable exists when using object destructuring

You can use || & if required provide default values while destructuring.

function print(user) {
const { fname = "Anonymous", lname = "Panda" } = user.fullname || {};

console.log(`Hello ${fname} ${lname}`);
}

print({ fullname: { fname: "John", lname: "Doe" } });
print({});
print({ fullname: null });

Is !obj[key] a good practice to check the existence of an object's property in JavaScript?

You should use the in operator:

"key" in obj // true, regardless of the actual value

if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty:

obj.hasOwnProperty("key") // true

For performance comparison between the methods that are in, hasOwnProperty and key is undefined, check this reference

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.

Detecting an undefined object property

The usual way to check if the value of a property is the special value undefined, is:

if(o.myProperty === undefined) {
alert("myProperty value is the special value `undefined`");
}

To check if an object does not actually have such a property, and will therefore return undefined by default when you try to access it:

if(!o.hasOwnProperty('myProperty')) {
alert("myProperty does not exist");
}

To check if the value associated with an identifier is the special value undefined, or if that identifier has not been declared:

if(typeof myVariable === 'undefined') {
alert('myVariable is either the special value `undefined`, or it has not been declared');
}

Note: this last method is the only way to refer to an undeclared identifier without an early error, which is different from having a value of undefined.

In versions of JavaScript prior to ECMAScript 5, the property named "undefined" on the global object was writeable, and therefore a simple check foo === undefined might behave unexpectedly if it had accidentally been redefined. In modern JavaScript, the property is read-only.

However, in modern JavaScript, "undefined" is not a keyword, and so variables inside functions can be named "undefined" and shadow the global property.

If you are worried about this (unlikely) edge case, you can use the void operator to get at the special undefined value itself:

if(myVariable === void 0) {
alert("myVariable is the special value `undefined`");
}


Related Topics



Leave a reply



Submit