1

I have an array of objects and I'm trying to update values in the array based on one of the object's keys.

I'm having difficulty storing my Key as a variable.

In this instance the object looks like so

enter image description here

If I'm to store my Object Key as a variable it fails and just adds the new element

    let keyDataField = 'AUDCASH';
    for (let i = this.CellRow + 1; i < this.cash2.length; i ++)
    {
      this.cash2[i].keyDataField = 0;
    };

If it's hardcoded it works

    for (let i = this.CellRow + 1; i < this.cash2.length; i++) {
      this.cash2[i].AUDCASH = 0;
    };

Any idea on how i can pass a variable please?

Glenn Sampson
  • 1,188
  • 3
  • 12
  • 30

2 Answers2

1

it needs to be in []

let keyDataField = 'AUDCASH';
for (let i = this.CellRow + 1; i < this.cash2.length; i ++)
{
  this.cash2[i][keyDataField] = 0;
};

see how when you are using the variable i, you can't just do cash2.i, same goes with any other variable you want to use as a key. What it is currently doing is looking for a key called keyDataField rather than what is in the keyDataField variable

Anis Jonischkeit
  • 914
  • 7
  • 15
0

The first case doesn't work for you because in

let keyDataField = 'AUDCASH';
for (let i = this.CellRow + 1; i < this.cash2.length; i ++)
{
  this.cash2[i].keyDataField = 0;
};

you are trying to set the key keyDataField a value and the dot notation doesn't resolve the variable for you.

You should be using the brackets notation

this.cash2[i][keyDataField] = 0;
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400