1

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

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.