我想将 json api 标准文档简化为骆驼版本。我能够制作一个camelCase对象和单个原始类型键。
我希望所需的输出是每个键camelCase。所以在上面的例子中first-name会变成firstName,snake-case会变成snakeCase。我面临的问题是如何使用我现在使用的相同递归调用来处理对象数组。
import _ from "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 => {
if (_.isPlainObject(obj[key])) {
return toCamelCase(obj[key]);
}
if (_.isArray(obj[key])) {
// console.log(obj[key]);
obj[key].forEach(element => {
console.log(element);
});
//obj[key].foreach(element_ => toCamelCase);
}
if (needsCamelCase(key)) {
obj[strToCamelCase(key)] = obj[key];
delete obj[key];
}
});
return obj;
};
// toCamelCase(data);
console.log(toCamelCase(data));
这是一个代码框: https ://codesandbox.io/s/javascript-l842u
茅侃侃
相关分类