Created
December 8, 2017 18:27
-
-
Save betafcc/1e90ffddba0047dad901465b1174bf34 to your computer and use it in GitHub Desktop.
Mapping over plain objects in JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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