You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript/JavaScript中动态向对象push属性报错及需求

Fixing "Cannot read property 'push' of undefined" in Your CounterType Code

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 (like undefined). 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:31:14