Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamically add properties to object

In Javascript I created an object like this:

this.view.objectExample.accessibilityConfig= {
    'propertyA': 1,
    'PropertyB': 2,
    'PropertyC': 3
};

I’m trying to add a new property in runtime but get "Cannot set properties of undefined" error.

Code used example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this.view.objectExample.accessibilityConfig.propertyD['flag'] = true;

What’s the proper way to set a new property like this?

Also tried like this:

this.view.objectExample.accessibilityConfig.propertyD.flag = true;

>Solution :

Because there is no propertyD in the original object, so accessibilityConfig.propertyD is undefined.

You can dynamically add properties to an object, but that object has to exist first. This is true for every level of an object’s hierarchy. So before you can do this:

this.view.objectExample.accessibilityConfig.propertyD.flag = true;

You’d have to do this:

this.view.objectExample.accessibilityConfig.propertyD = {};

Or you can do both at the same time:

this.view.objectExample.accessibilityConfig.propertyD = { flag: true };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading