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));
添加回答
舉報