如何在空对象中添加新的键和值?

时间:2019-09-30 10:59:37

标签: javascript angular object

我有一个null对象。我想在其中添加动态键和对象。

尝试

this.myObj[`${dayValue}`] = {};  //1

this.withDayTimeSlot[dayValue] = [targetValue];

错误

TypeError: Cannot set property '5' of null at ...

我的动态对象将如下所示。

{
  '5':[],
  '6':[]
}

1 个答案:

答案 0 :(得分:2)

您无法在null对象中设置属性。首先需要将其初始化为空对象{}

this.myObj = {};
this.myObj[`${dayValue}`] = []; // [] since your desired value in the object is an empty array [] and not an empty object {}