【问题标题】:push() property to an object dynamically Typescript/Javascript动态地向对象推送()属性Typescript / Javascript
【发布时间】:2018-07-06 17:41:07
【问题描述】:

我正在尝试将push() 的属性指向对象counterType,但出现以下错误:

未捕获的类型错误:无法读取未定义的属性“推送”

我正在尝试从 JSON 文件中获取特定数据并将其添加到 counterType 对象。我的代码如下:

    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;
        if (row.hasOwnProperty("SYSTEM")) {
            counterType[row_system].push({ name: row_system, checked: true });
            // counterType[row_system] = "name: " + row_system + ", checked: " + true;
        }
    }

此行有效,但每次迭代仅添加一个属性,因为它只是将 counterType[row_system] 的值每次重新定义为同一事物:

// counterType[row_system] = "name: " + row_system + ", checked: " + true;

我想在每次迭代时不断将{ name: row_system, checked: true } 添加到对象中。

【问题讨论】:

  • counterType[row_system] 未定义。
  • 您可以在counterType[row_system].push(...)之前添加counterType[row_system] === undefined &amp;&amp; (counterType[row_system] = [])语句。
  • @Titus 这是如何以及为什么起作用的?这是您知道解决此问题的唯一方法吗?
  • @StefanNicolaou 它的作用是检查counterType[row_system] 是否为undefined,如果是,则将其设置为空数组。您可以使用 if 语句 if(!counterType[row_system]){ counterType[row_system] = []; } 来做同样的事情

标签: javascript json typescript object


【解决方案1】:

替换

let counterType: any = {};

与:

let counterType: any = [];

由于您将其用作数组并推入其中。

你也不需要为推送设置索引:

counterType[row_system].push({ name: row_system, checked: true });

可以替换为

counterType.push({ name: row_system, checked: true });

【讨论】:

  • 我想设置一个索引,因为我将为多个 JSON 文件运行类似的循环,它们都将被放入 counterType 对象中
【解决方案2】:

你可以这样做

public interface counterTypesModel ={
   name :any,
   checked : boolean
}
counterTypesArray : counterTypesModel = [];
counterTypesArray.push({'name': row_system,'checked' : true});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    • 2021-09-26
    • 1970-01-01
    • 2013-07-21
    • 2020-07-08
    • 1970-01-01
    相关资源
    最近更新 更多