【发布时间】:2019-08-12 22:19:10
【问题描述】:
我正在尝试了解此递归函数如何将 JSON 键转换为 camelCase。有人可以对每一行发表评论和/或添加解释吗?谢谢!
function toCamel(o) {
var newO, origKey, newKey, value;
if (o instanceof Array) {
return o.map(function(value) {
if (typeof value === 'object') {
value = toCamel(value);
}
return value;
});
} else {
newO = {};
for (origKey in o) {
if (o.hasOwnProperty(origKey)) {
newKey = (origKey.charAt(0).toLowerCase() + origKey.slice(1) || origKey).toString();
value = o[origKey];
if (value instanceof Array || (value !== null && value.constructor === Object)) {
value = toCamel(value);
}
newO[newKey] = value;
}
}
}
return newO;
}
【问题讨论】:
-
没有观察到 JSON。您说的是 JavaScript 对象,而不是 JSON。 JSON总是是一个纯字符串。
-
对我的回答有什么想法吗?
标签: javascript json recursion