Skip to content

Instantly share code, notes, and snippets.

@thatguychrisw
Last active October 17, 2020 17:23
Show Gist options
  • Save thatguychrisw/646c0d73e2bc9046073fe12529f7f3a2 to your computer and use it in GitHub Desktop.
Save thatguychrisw/646c0d73e2bc9046073fe12529f7f3a2 to your computer and use it in GitHub Desktop.
A functional approach to lower casing object values
import { expect } from 'chai'
const lowerCaseValues = (object, paths) =>
Object.assign(lowerCaseObjectValues(object), partialObject(object, paths))
const lowerCaseObjectValues = object => {
return Object.entries(object).reduce((updated, [key, value]) => {
const isString = typeof value === 'string'
const isObject = typeof value === 'object'
if (isObject) {
updated[key] = lowerCaseObjectValues(value)
return updated
}
updated[key] = isString ? value.toLowerCase() : value
return updated
}, {})
}
const partialObject = (object, paths) => {
if (!paths.length) {
return object
}
const partialObject = {}
paths.forEach(path => {
const nodes = path.split('.')
const pathValue = nodes.reduce((o, i) => o[i], object)
let partial = partialObject
while (nodes.length > 1) {
const node = nodes.shift()
partial = partial[node] = partial[node] || {}
}
partial[nodes[0]] = pathValue
})
return partialObject
}
describe('testing', () => {
it('accepts ignore keys nested keys as using . notation', () => {
const control = {
name: 'Daniel',
foo: {
bar: 'Wiz',
deeply: {
nested: 'Control'
}
}
}
const expected = {
name: 'daniel',
foo: {
bar: 'Wiz',
deeply: {
nested: 'Control'
}
}
}
expect(lowerCaseValues(control, ['foo.bar', 'foo.deeply.nested'])).to.eql(expected)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment