Skip to main content

transform()

transform<T, Acc>(object, iteratee, accumulator): Acc

Iterates over own enumerable properties of object and accumulates a result.

๐Ÿ’Ž Why is this a Hidden Gem?

A more flexible alternative to reduce, designed specifically for objects.

DEPRECATED

Use Object.entries().reduce() directly instead.


Type Parametersโ€‹

T: T extends objectโ€‹

The type of the object.

Acc: Accโ€‹

The type of the accumulator.


Parametersโ€‹

object: Tโ€‹

The object to iterate over.

iteratee: (accumulator, value, key, object) => voidโ€‹

The function invoked per iteration.

accumulator: Accโ€‹

The initial value.


Returns: Accโ€‹

The accumulated value.


See Alsoโ€‹

Object.entries() - MDN


Sinceโ€‹

2.0.0


Also known asโ€‹

transform (Lodash, es-toolkit) ยท โŒ (Remeda, Radashi, Ramda, Effect, Modern Dash, Antfu)


Exampleโ€‹

// โŒ Deprecated approach
transform({ a: 1, b: 2, c: 1 }, (result, value, key) => {
(result[value] ||= []).push(key);
}, {} as `Record<number, string[]>`);
// => { 1: ['a', 'c'], 2: ['b'] }

// โœ… Recommended approach
Object.entries({ a: 1, b: 2, c: 1 }).reduce((result, [key, value]) => {
(result[value] ||= []).push(key);
return result;
}, {} as `Record<number, string[]>`);
// => { 1: ['a', 'c'], 2: ['b'] }

How it works?โ€‹

Iterates object properties and accumulates a result.

Processing Flowโ€‹

Common Inputsโ€‹

ObjectIterateeInitialResult
{a: 1, b: 2}(r,v,k) => r[v] = k{}{1: 'a', 2: 'b'}

warning Deprecated: Use Object.entries().reduce() directly.


Use Casesโ€‹

Accumulate from object ๐Ÿ“Œโ€‹

Iterate and accumulate result.

Object.entries(obj).reduce((acc, [key, value]) => {
// transform logic
return acc;
}, initialValue);

Group by valueโ€‹

Group keys by their values.

const grouped = Object.entries({ a: 1, b: 2, c: 1 }).reduce(
(acc, [k, v]) => {
(acc[v] ||= []).push(k);
return acc;
},
{} as Record<number, string[]>
);
// { 1: ['a', 'c'], 2: ['b'] }

Build an inverted lookup mapโ€‹

Create a reverse mapping from values to keys for fast lookups. Useful for enum reverse lookups, code-to-label mappings, and search indexes.

const statusCodes = { ok: 200, notFound: 404, serverError: 500 };

const codeToName = transform(statusCodes, (result, value, key) => {
result[value] = key;
}, {} as Record<number, string>);
// => { 200: "ok", 404: "notFound", 500: "serverError" }

console.log(codeToName[404]); // => "notFound"

Filter and transform an object in one passโ€‹

Select and reshape object properties in a single iteration. More efficient than chaining filter + map on entries.

const rawConfig = { host: "localhost", port: 3000, debug: "", verbose: null, timeout: 5000 };

const cleanConfig = transform(rawConfig, (result, value, key) => {
if (value != null && value !== "") {
result[key] = value;
}
}, {} as Record<string, unknown>);
// => { host: "localhost", port: 3000, timeout: 5000 }