我正在构建一个函数,该函数创建具有动态属性(以年和月为键)的嵌套对象。
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句