Created
June 5, 2017 15:04
-
-
Save pjanuario/7f6b33379ecc3900a4870d9db29f1fa5 to your computer and use it in GitHub Desktop.
Module to do a deep conversion of a object into a camelCase
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
import _ from 'lodash'; | |
export default function toCamelCase(obj) { | |
if (!_.isObject(obj)) { return obj; } | |
if (_.isArray(obj)) { | |
return obj.map(toCamelCase); | |
} | |
return _.reduce(obj, (memo, value, key) => { | |
// for recursive key conversion, | |
// it checks that a value is a plain object or an array | |
if (_.isPlainObject(value) || _.isArray(value)) { | |
// recursively update keys of any values that are also objects | |
value = toCamelCase(value); | |
} | |
memo[_.camelCase(key)] = value; | |
return memo; | |
}, {}); | |
}; | |
import toCamelCase from './toCamelCase'; | |
describe.only('API::Mapper', () => { | |
describe('#toCamelCase', () => { | |
describe('when not a object', () => { | |
it('should retrieve the value when is a boolean', () => { | |
toCamelCase(true).should.be.eql(true); | |
}); | |
it('should retrieve the value when is string', () => { | |
toCamelCase("some").should.be.eql("some"); | |
}); | |
}); | |
it('should retrieve a camel case object', () => { | |
toCamelCase({ my_prop: true}).should.be.eql({myProp: true}); | |
}); | |
it('should retrieve a deep camel case object', () => { | |
toCamelCase({ my_prop: { other_prop: true }}) | |
.should.be.eql({ myProp: { otherProp: true }}); | |
}); | |
it('should retrieve a array with camel case objects', () => { | |
toCamelCase([{ my_prop: true}]).should.be.eql([{myProp: true}]); | |
}); | |
it('should retrieve a deep camel case array objects', () => { | |
toCamelCase({ my_prop: [{ other_prop: true }]}) | |
.should.be.eql({ myProp: [{ otherProp: true }]}); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment