Home > OS >  Dynamically add properties to object
Dynamically add properties to object

Time:09-27

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:

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;

CodePudding user response:

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 };
  • Related