Search code examples
javascriptarrayscountermap-function

counter in map() functions does not work, why?


I have a problem. It seems that my counter does not work and does not change to 1, so my questioncontext variable is always "Fragekontext0" for every item in the map function. Do you know why? Here is the code:

Object.keys(editorJSON).map((key) => {
  let questioncounter = 0;
  if (editorJSON[key].name === "Frage") {
    let questioncontext = "Fragekontext" + questioncounter;
    someCode
    );
  }
  questioncounter += 1;
  return "Success";
});

};


Solution

  • A new questioncounter variable is declared in every map callback function. To have each callback access the same questioncounter variable, place let questioncounter = 0; outside the map function.