Reputation: 1978
I'm trying to build a new nested object based on bracked notation. my syntax is
metaObj[subCat][attribute] = value;
and I have these variables; My goal is to achieve this structure
metaObj = {
chart : {
x: "random",
y: 123
},
data : {
x: "random",
y: 123
}
}
I should build it dynamically since the attribute names and categories might change in every scenario
I receive this error though
Uncaught TypeError: Cannot set property ---- of undefined
Upvotes: 1
Views: 490
Reputation: 4684
That's becoz you are trying to set the value for an object that is not yet created. Assuming that the metaObj is already initialized with {}
if(!metaObj[subCat]) {
metaObj[subCat]= {};
metaObj[subCat][attribute] = value;
} else {
metaObj[subCat][attribute] = value;
}
Upvotes: 0
Reputation: 352
The error says that it cannot set property of undefined because the subCat
is undefined.
A solution would be to first define it as an object and then do your thing.
metaObj = {};
metaObj[subCat] = {}; // define the subCat ( metaObj: {subCat: {}})
metaObj[subCat][attribute] = value;
Upvotes: 2