0

I have code like below

for (var key in array) {
  var name = array[key];
  console.log(name);

  line[val].setResultTableFormatter((builder, series, xValue, yValue) => {
    return builder.addRow(name);
  });
}

Here array length is 5 and console.log(name) is printed 5 times, but setResultTableFormatter is executed only once with the last array value. How to run it all 5 times?

I tried to add await like explained in other StackOverflow answers, still, It gets executed only once.

Alyson Maia
  • 802
  • 5
  • 14
Gracie williams
  • 1,287
  • 2
  • 16
  • 39

1 Answers1

1

Without knowing what setResultTableFormatter does, it looks like the function will run all those 5 times, but the function setResultTableFormatter just overwrites the first 4 times.

You can try and add a console.log inside the setResultTableFormatter like this:

for (var key in array) {
  var name = array[key];
  console.log(name);

  line[val].setResultTableFormatter((builder, series, xValue, yValue) => {
     console.log('add row', name);
     return builder.addRow(name);
  });
}

Or you could run the for loop inside the setResultTableFormatter function (probably, again, I don't know what it does)

line[val].setResultTableFormatter((builder, series, xValue, yValue) => {
  for(var key in array) {
    builder.addRow(array[key]);
  }
  return builder;
});

As a side note, using let or const would be better here. Here's an article about why it's better. Long story short in this case, the var will be available outside of the for loop, which isn't necessary. Using let or const (if you're not changing the variable afterwards) will do the job just fine and it'll stay inside the loop.

Bart Versluijs
  • 186
  • 1
  • 8