Andre Gomez
Andre Gomez

Reputation: 91

How to access dynamic named property inside another object in angular?

In Angular 8 I created an object from a JSON, there is a dynamic property, I do not know the name of it before runtime. Inside another object I need to call that dynamic property's value, but because that happens at runtime, it does not exist, therefore it won't compile.

Is there a way to achieve this?

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)

Upvotes: 1

Views: 473

Answers (1)

satanTime
satanTime

Reputation: 13539

You need to define its type, or simply use any to speedup the stings. to use res.data[i].text as a key use square brackets [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);
}

Upvotes: 1

Related Questions