Aller au contenu principal

forIn()

forIn<T>(object, iteratee): void

Iterates over own and inherited enumerable string keyed properties of an object.

DEPRECATED

Use for...in loop directly instead.


Type Parameters

T: T extends object

The type of the object.


Parameters

object: T

The object to iterate over.

iteratee: (value, key, object) => void

The function invoked per iteration.


Returns: void


Since


See Also

for...in - MDN 2.0.0


Also known as

forEachObj (Remeda) · forIn (Lodash, es-toolkit) · ❌ (Radashi, Ramda, Effect, Modern Dash, Antfu)


Example

// ❌ Deprecated approach
forIn({ a: 1, b: 2 }, (value, key) => console.log(key, value));

// ✅ Recommended approach
for (const key in { a: 1, b: 2 }) {
console.log(key, obj[key]);
}

How it works?

Iterates over own and inherited enumerable properties. Deprecated: Use for...in loop directly.

Native Equivalent

// ❌ forIn(obj, fn)
// ✅ for (const key in obj) fn(obj[key], key, obj)

Use Cases

Iterate own properties 📌

Loop over object's own properties.

for (const key of Object.keys(obj)) {
console.log(key, obj[key]);
}

Process each property

Apply function to each property.

Object.entries(obj).forEach(([key, value]) => {
process(key, value);
});

Validate all properties

Check each property value.

for (const [key, value] of Object.entries(config)) {
if (value === undefined) throw new Error(`Missing: ${key}`);
}