ESLint does not allow

I have an object

currentValues= {hey:1212, git:1212, nmo:12121}

and I use for this:

for (const key in currentValues) {
    if (Object.prototype.hasOwnProperty.call(currentValues, key)) {
        yield put(setCurrentValue(key, currentValues[key]));
    }
}

ESLint shows me an error that says:

ESLint: for..in iteration loops throughout the prototype chain, which you almost never need. Use Object. {Keys, values, entries} and iterating over the resulting array. (Unlimited syntax

How do I change the code?

+18
source share
6 answers

It says:

Use object. {keys, values, records} and iterate over the result array.

So you can do something like this to get the keys of an object as an array, and then scroll through the keys to make the necessary changes.

currentValues= {hey:1212, git:1212, nmo:12121}

Object.keys(currentValues).forEach(function(key) {
  yield put(setCurrentValue(key, currentValues[key]));
})
Run codeHide result
+26
source

:

const keys = Object.keys(currentValues);
const values = Object.values(currentValues);
for (let i = 0; i < keys.length; i += 1) {
    yield put(setCurrentValue(keys[i], values[i]));
}

ESLint.

+6

,

var myValuesInArray = Object.values(currentValues);
+2

I know this is similar to the above, but here is a complete example:

const data = res.data;
const keys = Object.keys(data);
const values = Object.values(data);

for (let i = 0; i <= keys.length; i += 1) {
  if (Object.prototype.hasOwnProperty.call(values, i)) {
     this.rows.push({
        name: values[i].name,
        email: values[i].email,
        address: values[i].address,
        phone: values[i].phone,
        role: values[i].role,
  });
 }
}
0
source

try this instead:

Object.keys(currentValues).map(key => (yield put(setCurrentValue(key, currentValues[key]))));
0
source

Usage for...inwill iterate over all properties, including those from the prototype object. I'm not sure why you do Object.prototype.hasOwnProperty.call(currentValues, key) not just: currentValues.hasOwnProperty(key). I think this should make ESLint know that you are filtering only for your own properties.

However, I suggest using for (const key of Object.keys())one that is more semantic.

-2
source

Source: https://habr.com/ru/post/1676484/


All Articles