简体   繁体   中英

How to prevent object properties from being overwritten

I'm building a function that creates a nested object with dynamic properties which has the year and month as keys.

 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)

The output only captures the last index and the first index instead

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

How do I make sure that the other months are not missed out?

You are overwriting the complete object-key at

sixMonthSummary[year] = {}

try to insert the existing object with a spread-operator to include all prev months.

 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)

It's because you're resetting the year key each iteration of the loop. Try something like

if(!sixMonthSummary[year]) {
 sixMonthSummary[year] = {};
}

sixMonthSummary[year][month] = {
 rent: "",
 income: "",
 expenses: "",
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM