I have warning from ReactJS
Function declared in a loop contains unsafe references to variable(s) 'level'
How to fix my loop? I don't know how to send ver level and change it in my infinity loop.
const catTree = [{"id": "963",
"level": 1},
{"id": "998",
"level": 2},
{"id": "1636",
"level": 2}];
let cats = [];
let level = 1;
let catsCand = [];
for (; cats.length < 2;) {
cats = catTree.filter((cat) => {
return cat.level === level;
});
if (!catsCand.length) {
// if all levels give less then 2 cats
catsCand = cats;
}
level += 1;
if (!cats.length) { // if level is not exists
cats = catsCand;
break;
}
}
Thanks!
Answer: Just move level var to "for" loop.
let cats = [];
// показать корень
let catsCand = [];
for (let level=1; cats.length < 2; level++) {
cats = catTree.filter((cat) => {
return cat.level === level;
});
if (!catsCand.length) {
// если все уровни дадут меньше 2 категорий
catsCand = cats;
}
if (!cats.length) { // если пошел несуществующий уровень
cats = catsCand;
break;
}
}