TypeScript/JavaScript中动态向对象push属性报错及需求
Hey there, let's break down what's going wrong here and fix it step by step.
The Root Cause
You're hitting that TypeError because when you first try to call counterType[row_system].push(), the property counterType[row_system] doesn't exist yet—it's undefined. push() is an array method, but you're trying to call it on a non-existent value.
Your commented code works but overwrites data because you're assigning a string directly to counterType[row_system] each time, instead of building a collection of items for each system.
The Fix
We need to ensure each row_system key in counterType points to an array before we try pushing items into it. Here's the adjusted code:
let ret = JSON.parse(this.responseText); let counterType: any = {}; for (let i = 0; i < ret.topdownGranularities.TOPDOWN_SYSTEM_DATA.rows.length; i++) { let row = ret.topdownGranularities.TOPDOWN_SYSTEM_DATA.rows[i]; let row_system = row.SYSTEM; // Initialize the array if it doesn't exist for this system if (!counterType[row_system]) { counterType[row_system] = []; } // Now we can safely push the object into the array counterType[row_system].push({ name: row_system, checked: true }); }
What This Does
- Before pushing, we check if
counterType[row_system]is falsy (likeundefined). If it is, we create an empty array for that key. - Then we add your
{ name: row_system, checked: true }object to the array. This way, each system will accumulate items instead of getting overwritten with each iteration.
Bonus: Cleaner Loop (Optional)
You can use a for...of loop to make the code more readable and modern:
let ret = JSON.parse(this.responseText); let counterType: any = {}; const rows = ret.topdownGranularities.TOPDOWN_SYSTEM_DATA.rows; for (const row of rows) { const row_system = row.SYSTEM; if (!counterType[row_system]) { counterType[row_system] = []; } counterType[row_system].push({ name: row_system, checked: true }); }
This does the exact same job but cuts down on some boilerplate from the traditional for loop.
内容的提问来源于stack exchange,提问作者Stefan

