π Prefer the most specific Object iterable method.
πΌ This rule is enabled in the following configs: β
recommended, βοΈ unopinionated.
π§ This rule is automatically fixable by the --fix CLI option.
Prefer the most direct Object iterable method for the data being used.
Choosing the method that matches the values consumed avoids creating keys or entries that the loop or callback never uses.
Use Object.values() when only values are needed, Object.entries() when both keys and values are needed, and Object.keys() when only keys are needed.
This rule reports forβ¦of loops, Object.keys().map() callbacks, and Object.entries() callbacks for .map(), .every(), .some(), .findIndex(), .findLastIndex(), .flatMap(), .forEach(), .reduce(), and .reduceRight().
Object.entries().reduce() and Object.entries().reduceRight() are only reported when an initial value is provided.
// β
for (const key of Object.keys(object)) {
foo(object[key]);
}
// β
for (const value of Object.values(object)) {
foo(value);
}// β
Object.keys(object).map(key => foo(object[key], key));
// β
Object.entries(object).map(([key, value]) => foo(value, key));// β
Object.entries(object).reduce((result, [key, value]) => result + value, 0);
// β
Object.values(object).reduce((result, value) => result + value, 0);// β
for (const [key] of Object.entries(object)) {
foo(key);
}
// β
for (const key of Object.keys(object)) {
foo(key);
}When a value access uses a TypeScript cast on the object, the cast is moved onto the iterable method argument so the inferred element type is preserved.
// β
for (const key of Object.keys(object)) {
foo((object as Record<string, unknown>)[key]);
}
// β
for (const value of Object.values(object as Record<string, unknown>)) {
foo(value);
}