Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.