Skip to content

Instantly share code, notes, and snippets.

@betafcc
Created December 8, 2017 18:27
Show Gist options
  • Save betafcc/1e90ffddba0047dad901465b1174bf34 to your computer and use it in GitHub Desktop.
Save betafcc/1e90ffddba0047dad901465b1174bf34 to your computer and use it in GitHub Desktop.
Mapping over plain objects in JS
// objMap(x => x*x, {a: 2, b: 3}) -> {a: 4, b: 9}
const objMap = (f, obj) =>
Object
.entries(obj)
.reduce((acc, [k, v]) =>
(acc[k] = f(v, k, obj), acc)
, {});
// Need this function or equivalent to deep map
const isPlainObject = require('lodash.isplainobject');
// objDeepMap(x => x*x, {a: 2, b: {c: 3}}) -> {a: 4, b: {c: 9}}
const objDeepMap = (f, obj) =>
Object
.entries(obj)
.reduce((acc, [k, v]) =>
isPlainObject(v)
? (acc[k] = objDeepMap(f, v), acc)
: (acc[k] = f(v, k, obj), acc)
, {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment