[英]Assign a Value to an Object inside another object that has dynamically assigned keys
我有一個對象,其中數字月份是其他對象的鍵,其中包含鍵的年份和初始值的零。
MonthRow : {
1 : {2017:0,2018:0},
2 : {2017:0,2018:0},
3 : {2017:0,2018:0},
4 : {2017:0,2018:0},
5 : {2017:0,2018:0},
6 : {2017:0,2018:0}
}
查詢后,我使用下面的代碼來設置每個對象的值
Object.keys(MainData.MonthRow).forEach(function(key){
MainData.block.forEach(function(element,i,block){
if(key == element.month){
MainData.year.forEach(function(year, j, years){
if(element.year == year && key == element.month){
console.log("This is the Sale: ", element.Sale, "This is the year ", year, key);
console.log(MainData.MonthRow[key], "This is the Month Key");
console.log(MainData.MonthRow[key][year], "This is the year and key");
MainData.MonthRow[key][year]=element.Sale;
console.log(MainData.MonthRow)
}
})
}
});
但是在使用MonthRow [key] [year] = element.Sale分配值之后; 它將值分配給所有月份。
我的守時性問題是如何為obj.key.year = value分配值,其中key和year是變量?
在JSFiddle中重新創建取得了預期的結果,但是在Sails框架上無法正常工作
問題在於MonthRow
內的所有子對象都引用同一個對象( MainData.years
),換句話說, MainData.years === MonthRow['1'] === MonthRow['2'] === ...
。 因此,對這些子對象之一的更改也將反映在MainData.years
所有子對象上。 這是問題的示范:
var objA = {}; var objB = objA; // objA is not copied to objB, only a reference is copied // objA and objB are pointing/referencing the same object objB.foo = "bar"; // changes to one of them ... console.log(objA); // ... are reflected on the other
為了解決這個問題,你需要克隆的對象MainData.years
分配給對象的每個屬性之前MonthRow
,這樣子對象都將是不同的對象。 您可以這樣使用Object.assign
:
MonthRow = {
'1': Object.assign({}, MainData.years),
'2': Object.assign({}, MainData.years),
...
}
邊注:
可以將問題中的代碼重構為較短的代碼,因為您無需循環MonthRow
或MainData.year
的鍵,只需循環MainData.block
,對於每個元素,只需檢查當前元素的年份包含在MainData.year
(使用indexOf
或includes
),然后使用元素的年份和月份更新MainData.MonthRow
:
MainData.block.forEach(function(element) {
if(MainData.year.indexOf(element.year) !== -1) {
MainData.MonthRow[element.month][element.year] = element.sale;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.