我试图将多个元素分配给一个对象,但没有成功。数据被覆盖而不是添加。我对此很陌生,因此我不确定 Object.assing()
是否是正确的选择。如何向一个对象添加多组数据?
伪代码
- 选择开始日期
- 添加到对象
- 选择结束日期
- 添加到对象
- 获取中间日期并添加到对象
代码
_selectDate = obj => {
let selection = {}
const { startDate, endDate } = this.state
if (!startDate) {
Object.assign(selection, {
[obj.dateString]: { startingDay: true, color: 'black', textColor: 'white' },
})
} else {
Object.assign(selection, {
[obj.dateString]: { endingDay: true, color: 'black', textColor: 'white' },
})
}
this.setState({
startDate: !startDate,
test: selection,
})
}
期望的结果
{
'2018-08-20': { startingDay: true, color: 'black', textColor: 'white' },
'2018-08-21': { selected: true, color: 'black', textColor: 'white' },
'2018-08-22': { selected: true, color: 'black', textColor: 'white' },
'2018-08-04': { endingDay: true, color: 'black', textColor: 'white' },
}
最佳答案
每次调用时创建新对象的问题:
let selection = {}
这就是为什么您无法“累积”此数据的原因。
要解决此问题,您应该从您所在的州获取它,如下所示:
let selection = this.state.test
然后(在 if 语句中)进行赋值:
selection = {
...selection,
[obj.dateString]: {
endingDay: true,
color: 'black',
textColor: 'white'
},
}
关于Javascript — 如何将多个元素分配给一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51808529/