Alex
Alex

Reputation: 1391

Avoid React "no-unused-vars" error with loop

I am generating an array of objects based on the quantity of items in another array. Pretty simple, I'm just doing the following, which works fine.

for(let i in myArray){
  newArray.push({
    var1: someFunctionValue(),
    var2: anotherFunctionValue()
  });
}

However, because "i" is not being used, React (ESLint?) gives me the warning 'i' is assigned a value but never used - no-unused-vars.

Is there a better way I should be doing this? I don't really see a way to achieve what I want without producing this error.

Upvotes: 1

Views: 2484

Answers (3)

Tomiwa
Tomiwa

Reputation: 1044

Based on this answer. You can also try declaring the variable outside the loop.

For my use case I needed a break statement so forEach() wouldn't work for me.


let i = null;
for(i in myArray){
  if (i==='fooBar') {
     break;
   } 
    else {
        newArray.push({
        var1: someFunctionValue(i),
        var2: anotherFunctionValue()
  });

}


}

Upvotes: 1

Andrew Li
Andrew Li

Reputation: 57964

You're using a for-in loop over an array, without using the enumerable keys (indices). You should use Array#forEach instead, and since it accepts a callback, you can just omit any arguments:

myArray.forEach(() => { // No callback args
  newArray.push({
    var1: someFunctionValue(),
    var2: anotherFunctionValue()
  });
});

Also, now that I'm reading your variable names, it seems you're trying to do a mapping operation, as in for every element in myArray, you want a new one in newArray associated with each index. If that's the case, the better method is to Array#map your myArray:

const newArray = myArray.map(() => ({
  var1: someFunctionValue(),
  var2: anotherFunctionValue(),
}));

There's no need for any intermediacy and it's concise.

Upvotes: 5

Tholle
Tholle

Reputation: 112827

You could use forEach instead which doesn't need a variable:

myArray.forEach(() => {
  newArray.push({
    var1: someFunctionValue(),
    var2: anotherFunctionValue()
  });
});

Upvotes: 2

Related Questions