简体   繁体   中英

Check if a property exists on an object when the object may not exists either?

I can check if a property exists like so:

let myObject = {};
let exists = myObject.myProperty !== undefined;

But how can I check if the property exists when myObject is not defined either, the following errors:

// let myObject = {}; // do not set this
let exists = myObject.myProperty !== undefined;

There are several things at play here.
First, to check if the object exists in the current scope, you should use the typeof operator:

let objectExists = typeof myObject !== 'undefined'

this way, the interpreter won't throw an error.

Second, to check if the object has a specific property, it's still best to use the old in operator

let propertyExists = 'myProperty' in myObject

Both of these expressions return a boolean value, true or false.
So, for safe checking, you might use:

if(typeof myObject !== 'undefined' && myProperty in myObject) {
  // do your stuff
}

if you try to use the newer form of myObject?.myProperty it will still throw a ReferenceError if you haven't declared myObject

and if you use myObject.hasOwnProperty(myProperty) you might get a misleading result, if your object inherits from another and the property belongs to the ancestor

if myObject doesn't exist at all , use try/catch

let exists;
try {
exists = myObject.hasOwnProperty('myProperty');

}catch(err){
console.log(err.message) 
}

if it's null or undefined , Use ?. (optional chaining) operator:

let exists = myObject?.hasOwnProperty('myProperty');

Since the myObject variable might not be defined (as per your question), you must wrap your code with try/catch in order for the flow not to break:

 let exists = false; try{ // try to access "a" property of myObject exists = myObject?.a; } catch{ // because myObject is not defined, the catch block is invoked console.log("myObject", "is not defined") } console.log({exists})

There are several approaches for this

// let myObject = {}; // do not set this
let exists = myObject != null && myObject.hasOwnProperty("myProperty")
// let myObject = {}; // do not set this
let exists = myObject != null && "myProperty" in myObject

Edit:

if myObject has the potential to not only be null/undefind but of being not defined in the first place, this can be checked with a try-catch block like so:

 let exists; try { exists = myObject != null && myObject.hasOwnProperty("myProperty"); }catch(err){ exists = false; } console.log(exists)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM