我正在构建一个函数,该函数创建一个具有动态属性的嵌套对象,该对象以年和月为键。
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": ""
}
}
我如何确保不会错过其他月份?
答案 0 :(得分:1)
您正在覆盖完整的对象键
<块引用>sixMonthSummary[年] = {}
尝试使用 spread-operator 插入现有对象以包括所有上个月。
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)
答案 1 :(得分:1)
这是因为您在循环的每次迭代中都重置年份键。尝试类似
if(!sixMonthSummary[year]) {
sixMonthSummary[year] = {};
}
sixMonthSummary[year][month] = {
rent: "",
income: "",
expenses: "",
};