简体   繁体   English

使用括号表示法构建一个新的嵌套 object

[英]build a new nested object with bracket notation

I'm trying to build a new nested object based on bracked notation.我正在尝试基于方括号表示法构建一个新的嵌套 object。 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

The error says that it cannot set property of undefined because the subCat is undefined.该错误表明它无法设置未定义的属性,因为subCat未定义。

A solution would be to first define it as an object and then do your thing.一种解决方案是首先将其定义为 object,然后执行您的操作。

metaObj = {}; 
metaObj[subCat] = {}; // define the subCat ( metaObj: {subCat: {}})
metaObj[subCat][attribute] = value;

That's becoz you are trying to set the value for an object that is not yet created.那是因为您正在尝试为尚未创建的 object 设置值。 Assuming that the metaObj is already initialized with {}假设 metaObj 已经用 {} 初始化

if(!metaObj[subCat]) {
 metaObj[subCat]= {};
 metaObj[subCat][attribute] = value;
} else {
 metaObj[subCat][attribute] = value;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM