如何防止对象属性被覆盖



我正在构建一个函数,该函数创建一个嵌套对象,该对象具有以年和月为键的动态属性。

const sixMonthSummary = {};
// This will get data for the latest 6 months
for (let i = 0; i <= 6; i++) {
const currentDate = new Date();
const [, month, year] = new Date(
currentDate.setMonth(currentDate.getMonth() - i)
)
.toLocaleDateString("en-SG")
.split("/");
sixMonthSummary[year] = {
[month]: {
rent: "",
income: "",
expenses: "",
},
};
}
console.log(sixMonthSummary)

输出只捕获最后一个索引和第一个索引,而不是

"2020": {
"07": {
"rent": "",
"income": "",
"expenses": ""
}
},
"2021": {
"01": {
"rent": "",
"income": "",
"expenses": ""
}
}

我如何确保不会错过其他月份?

您正在覆盖上的完整对象密钥

sixMonthSummary〔year〕={}

尝试使用排列运算符插入现有对象,以包括以前的所有月份。

const sixMonthSummary = {};
// This will get data for the latest 6 months
for (let i = 0; i <= 6; i++) {
const currentDate = new Date();
const [, month, year] = new Date(
currentDate.setMonth(currentDate.getMonth() - i)
)
.toLocaleDateString("en-SG")
.split("/");
sixMonthSummary[year] = {
...sixMonthSummary[year],
[month]: {
rent: "",
income: "",
expenses: "",
},
};
}
console.log(sixMonthSummary)

这是因为在循环的每次迭代中都要重置年份键。试试之类的东西

if(!sixMonthSummary[year]) {
sixMonthSummary[year] = {};
}
sixMonthSummary[year][month] = {
rent: "",
income: "",
expenses: "",
};

最新更新