首页 > 解决方案 > 如何以角度访问另一个对象内的动态命名属性?

问题描述

在 Angular 8 中,我从 JSON 创建了一个对象,有一个动态属性,在运行前我不知道它的名称。在另一个对象中,我需要调用该动态属性的值,但因为这发生在运行时,它不存在,因此它不会编译。

有没有办法做到这一点?

let i = 0;
this.columns = [
      { name: 'total' },
    ];
    do {
      if (certainCondition) {
        this.column.push({ name: res.data[i].text })
      }
      this.rows.push({
        total: someNumber,
        res.data[i].text: someValue
      });
      i++;
    } while (res.data[i] != null)

标签: angulartypescriptobjectionic-frameworkruntime

解决方案


您需要定义它的类型,或者简单地使用它any来加速刺痛。用作res.data[i].text键使用方括号[res.data[i].text]: value

(res: any) => {
  let i = 0;
  this.columns = [
    { name: 'total' },
  ];
  do {
    if (certainCondition) {
      this.column.push({ name: res.data[i].text });
    }
    this.rows.push({
      total: someNumber,
      [res.data[i].text]: someValue
    });
    i++;
  } while (res.data[i] != null);
}

推荐阅读