Open Huauauaa opened 2 months ago
function camel (data) {
if (typeof data != 'object' || !data) return data
if (Array.isArray(data)) {
return data.map(item => camel(item))
}
const newData = {}
for (let key in data) {
let newKey = key.replace(/_([a-z])/g, (p, m) => m.toUpperCase())
newData[newKey] = camel(data[key])
}
return newData
}
// case.js
import _ from 'lodash';
function camelCase(str) {
return _.camelCase(str);
// return str.replace(/_([a-z])/g, (p, m) => m.toUpperCase());
}
export function toCamel(data) {
if (typeof data === 'string') {
return camelCase(data);
}
if (typeof data !== 'object' || !data) {
return data;
}
if (Array.isArray(data)) {
return data.map((item) => toCamel(item));
}
return Object.keys(data).reduce((res, key) => {
let value = data[key];
if (typeof value === 'object') {
value = toCamel(value);
}
res[camelCase(key)] = value;
return res;
}, {});
}
// case.test.js
import { toCamel } from '../case';
test('toCamel', () => {
expect(toCamel(null)).toBe(null);
expect(toCamel(undefined)).toBe(undefined);
expect(toCamel(1)).toBe(1);
expect(toCamel(0)).toBe(0);
expect(toCamel('first_name')).toBe('firstName');
expect(toCamel(true)).toBe(true);
expect(toCamel(true)).toBe(true);
expect(toCamel([])).toStrictEqual([]);
expect(toCamel({})).toStrictEqual({});
expect(toCamel({ firstName: null })).toStrictEqual({
firstName: null,
});
expect(toCamel({ firstName: undefined })).toStrictEqual({
firstName: undefined,
});
expect(toCamel({ firstName: 'Harvey' })).toStrictEqual({
firstName: 'Harvey',
});
expect(toCamel({ first_name: 'Harvey' })).toStrictEqual({
firstName: 'Harvey',
});
expect(toCamel({ First_Name: 'Harvey' })).toStrictEqual({
firstName: 'Harvey',
});
expect(toCamel([{ first_name: 'Harvey' }])).toStrictEqual([
{
firstName: 'Harvey',
},
]);
expect(
toCamel({ first_name: 'Harvey', favorite_thing: ['reading'] }),
).toStrictEqual({
firstName: 'Harvey',
favoriteThing: ['reading'],
});
});
Sent from PPHub