javascriptslickgrid

javascript variable key in loop


Using Slickgrid I am trying to set the CSS of a cell using setCellCssStyles method

for (var rowIndx = 1; rowIndx < movmentRows.length; rowIndx++) {
  grid.setCellCssStyles("disabled", {
    rowIndx: {
      san: "slick-cellreadonly",
      ean: "slick-cellreadonly",
    },
  });
}

I understand its because I am using a variable for a key in the for loop. But I don't understand how to make this work. I tried to replace rowIndx with [rowIndx] but I am getting syntax error, so I think my JavaScript is not ES6. Then I tried the following but this is also giving syntax error with -

Encountered '['and Expected keyword or brace.

for(var rowIndx=1;rowIndx<movmentRows.length;rowIndx++){
  var key = {};
  grid.setCellCssStyles("natCol-greyed", {
    key[rowIndx] : {
      sourceAccountNational: "slick-cellreadonly",
      excludeAccountNational: "slick-cellreadonly"
    }
  });
}

Please suggest.


Solution

  • People provide answers using different loops. But the loop isn't a problem here. Do not be ashamed of using the for loop. It is still the best.

    What's the fastest way to loop through an array in JavaScript?

    Let's get straight to the answer, You can do it without creating an additional key object. Your first workaround was almost correct, But since you want to use the value of rowIndx as the key, Just wrap it with [].

      grid.setCellCssStyles("natCol-greyed", {
          [rowIndx]: {
              sourceAccountNational: "slick-cellreadonly",
              excludeAccountNational: "slick-cellreadonly"
          }
      });