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