1 回答
TA贡献1842条经验 获得超21个赞
逻辑很简单:如果它是一个对象,只需调用toCamelCase,如果它是一个数组,则对其进行迭代以创建一个新数组。如果它是一个对象数组,用 转换它toCamelCase,如果它是一个其他东西的数组,保持原样。
解决方案可能如下所示:
const _ = require('lodash');
const data = {
id: 1,
type: "user",
links: { self: "/movies/1" },
meta: { "is-saved": false },
"first-name": "Foo",
"last-name": "Bar",
locations: ["SF"],
actors: [
{ id: 1, type: "actor", name: "John", age: 80 },
{ id: 2, type: "actor", name: "Jenn", age: 40 }
],
awards: [
{
id: 4,
type: "Oscar",
links: ["asd"],
meta: ["bar"],
category: "Best director",
'snake_case': 'key should be snakeCase'
}
],
name: { id: 1, type: "name", title: "Stargate" }
};
const needsCamelCase = str => {
return str.indexOf("-") > -1 || str.indexOf("_") > -1;
};
const strToCamelCase = function(str) {
return str.replace(/^([A-Z])|[\s-_](\w)/g, function(match, p1, p2, offset) {
if (p2) return p2.toUpperCase();
return p1.toLowerCase();
});
};
const toCamelCase = obj => {
Object.keys(obj).forEach(key => {
const camelCasedKey = needsCamelCase(key) ? strToCamelCase(key) : key;
const value = obj[key];
delete obj[key];
obj[camelCasedKey] = value;
if (_.isPlainObject(value)) {
obj[camelCasedKey] = toCamelCase(value);
}
if (_.isArray(value)) {
obj[camelCasedKey] = value.map(item => {
if (_.isPlainObject(item)) {
return toCamelCase(item);
} else {
return item;
}
});
}
});
return obj;
};
// toCamelCase(data);
console.log(toCamelCase(data));
添加回答
举报