我正在尝试push()
对象counterType
的属性,但我收到以下错误:
未捕获的TypeError:无法读取属性' push'未定义的
我试图从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 }
。
答案 0 :(得分:0)
替换
let counterType: any = {};
使用:
let counterType: any = [];
因为你将它用作数组并推入它。
此外,您不需要为推送设置索引:
counterType[row_system].push({ name: row_system, checked: true });
可以替换为
counterType.push({ name: row_system, checked: true });
答案 1 :(得分:0)
你可以做这样的事情
public interface counterTypesModel ={
name :any,
checked : boolean
}
counterTypesArray : counterTypesModel = [];
counterTypesArray.push({'name': row_system,'checked' : true});