Build a new object by mapping, renaming, or dropping entries
An API returns settings as a flat object, and the UI needs a slightly different shape: values converted, some keys renamed, some entries left out. Instead of writing one loop per screen, implement a single helper, mapEntries(object, mapper), that builds a new object from the entries of an existing one.
mapEntries(object, mapper) // => a new object
mapper(value, key, object) // => [newKey, newValue], or null / undefined to drop the entry
mapper once for each own enumerable string key of object, in Object.keys order, with the value, the key, and the original object.mapper returns a pair [newKey, newValue], the result gets newKey: newValue. newKey is a string or a number; numbers become string keys as usual.mapper returns null or undefined, the entry is left out.object.'__proto__' becomes an ordinary own property of the result. It must not change the result’s prototype.const pricesInCents = { basic: 900, pro: 2400, team: 7900 };
mapEntries(pricesInCents, (cents, plan) => [plan, cents / 100]);
// => { basic: 9, pro: 24, team: 79 }
const flags = { dark_mode: true, beta_search: false, new_nav: true };
mapEntries(flags, (on, key) => (on ? [key.replace('_', '-'), 'enabled'] : null));
// => { 'dark-mode': 'enabled', 'new-nav': 'enabled' }
mapEntries({ a: 1, b: 2, c: 3 }, (n) => [n % 2 ? 'odd' : 'even', n]);
// => { odd: 3, even: 2 } (c overwrites a)
mapEntries({}, () => ['x', 1]);
// => {} (mapper is never called)