Skip to content

Latest commit

Β 

History

History
76 lines (55 loc) Β· 2.15 KB

File metadata and controls

76 lines (55 loc) Β· 2.15 KB

prefer-object-iterable-methods

πŸ“ 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.

Examples

// ❌
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);
}