[英]Javascript — How to assign multiple elements to an object?
我試圖將多個元素分配給一個對象而沒有成功。 數據被覆蓋而不是添加。 我對此並不Object.assing()
,因此不確定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'
},
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.