Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save srdjan/5fc740d65d65b954534480c0d52446d2 to your computer and use it in GitHub Desktop.
Save srdjan/5fc740d65d65b954534480c0d52446d2 to your computer and use it in GitHub Desktop.
Transforming Deeply Nested Data
import {
always,
equals,
identity,
ifElse,
map,
partial,
} from 'ramda'
const isObject = input => input !== null && typeof input === 'object'
/**
* Like map but for deeply nested objects
*
* @param {Function} f function to apply
* @param {Object} obj
*/
const nestedMap = (f, obj) => map(ifElse(isObject, partial(nestedMap, [f]), f), obj)
// verify
nestedMap(x => x + 5, [1, [[[2]]]])
// [
// 6,
// [
// [
// [
// 7
// ]
// ]
// ]
// ]
nestedMap(x => x + 5, {a: 1, b: { c: { d: 2 }}})
// {"a":6,"b":{"c":{"d":7}}}
const inputData = { a: 1, b: { c: { d: 2 } }, e: null, f: 3 }
const outputData = { a: 1, b: { c: { d: 2 } }, e: '', f: 3 }
const transformFrom = data => nestedMap(ifElse(equals(null), always(''), identity), data)
const transformTo = data => nestedMap(ifElse(equals(''), always(null), identity), data)
console.log(equals(transformTo(transformFrom(inputData)), inputData))
console.log(equals(transformFrom(transformTo(outputData)), outputData))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment