Skip to main content

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}`);
}