Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if an object exists JavaScript

Tags:

javascript

I can't believe this question would not have been asked before, but I searched as much as I could and couldn't find it so here it goes.

I want to test if a dynamically built JavaScript object exists. However when I test this:

var myObject = {};
var dynamicName = "customName";

if(myObject[dynamicName].object == undefined){
  myObject[dynamicName].object = "something"; // Make an entry in the dynamic object
  alert("The object didn't exist, so we populated it");
}else{
  alert("The object already exist");
}

If the object doesn't exist and I try to run the above code I get an error saying "myObject[dynamicName] is undefined" and all javascript execution halts.

Is there a way to check if this object exists I want without causing such an error?

like image 432
YAHsaves Avatar asked Feb 22 '26 07:02

YAHsaves


2 Answers

If myObject[dynamicName] doesn't exist, you can't access its properties. Trying to access or assign a property of undefined causes an error.

You need to create the object, then you can create the property

if (myObject && myObject[dynamicName] && myObject[dynamicName].object !== undefined) {
    alert("The object already exists");
} else {
    myObject = myObject || {};
    myObject[dynamicName] = myObject[dynamicName] || {};
    myObject[dynamicName].object = something;
    alert("The object didn't exist, so we populated it");
}
like image 193
Barmar Avatar answered Feb 24 '26 21:02

Barmar


There is a shorter version, (almost) without clumsy if's

const myObject = {};
const dynamicName = 'customName';

const { [dynamicName]: obj = {} } = myObject;
if (obj.object == null) {
  obj.object = 'something'
  console.log('populated');
} else {
  console.log('existed');
}
myObject[dynamicName] = obj;

console.log(myObject)
like image 21
amankkg Avatar answered Feb 24 '26 19:02

amankkg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!