分配任意深度的对象

时间:2019-05-20 12:38:39

标签: javascript typescript

我正在尝试动态创建嵌套对象

但是,我当前的解决方案似乎有点麻烦

output["USER_PROFILE"] = {};
output["USER_PROFILE"][this.userId] = userProfile;

理想情况下,我可以这样写:

output["USER_PROFILE"][this.userId] = userProfile;

显然会产生:
Cannot set property '04c05a6a' of undefined

有没有办法告诉javascript在创建过程中的所有内容?

1 个答案:

答案 0 :(得分:4)

只需将键放在对象文字中:

output.USER_PROFILE = {
  [this.userId]: userProfile
};