我有一个从数据库(使用 Slim 和 Twig)获取的 JSON 对象,但有一个字段有时是大写,有时是小写,有时是驼峰式,等等。我希望这个字段变成 TitleCase .
我已经有一个将字符串转换为 TitleCase 的函数,我在将 JSON 转换为数组时使用了该函数(使用这些数组作为 jqWidgets 的源):
function toTitleCase(str) {
return str.replace(/\w\S*/g, function (txt) {return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
}
现在我想对 JSON 对象做同样的事情。我想到的是在使用 parseJSON() 之后迭代它们,在我想要的字段上使用我的函数,并在使用 JSON.stringify() 之后返回新对象;但我想知道您是否认为这是解决此问题的最佳方法,或者您是否有更好的想法(我不要求直接源代码)。
我的 JSON 示例(我需要 TitleCase 中的 nomFonction 和 nomEntite):
"[{"idFonction":"1","nomFonction":"Manager","nomEntite":"DIRECTION"},{"idFonction":"2","nomFonction":"Développeur","nomEntite":"SERVICE CONTROLE"},{"idFonction":"3","nomFonction":"Stagiaire","nomEntite":"SERVICE COMPTABILITE"},{"idFonction":"4","nomFonction":"rjeizjrze","nomEntite":"DIRECTION"}]"
最佳答案
因此,我做了我想做的事情,即迭代转换为数组的 JSON 对象并将其转换回 JSON。
代码:
// Converts a string to TitleCase
function toTitleCase(str) {
return str.replace(/\w\S*/g, function (txt) {return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
}
/**
* @jsonArray : the array to convert
* <...> : the fields to convert in the JSON
*/
function JSONToTitleCase(jsonArray /**/) {
s = $.parseJSON(jsonArray); // Array from the JSON
var args = Array.prototype.slice.call(arguments, 1); // the fields to convert
// for each JSON object
for (i=0; i < s.length; i++){
// for each field to convert to TitleCase
for (j = 0; j < args.length; j++){
// if the field exists
if (typeof s[i][args[j]] != "undefined"){
// convert it
s[i][args[j]] = toTitleCase(s[i][args[j]]);
}
}
}
// back to JSON
return JSON.stringify(s);
}
用法:
JSONToTitleCase(JSON_Array, fieldtoconvert1, fieldtoconvert2, ...);
就我而言:
JSONToTitleCase(fonctionsEnBase, "nomEntite", "nomFonction");
关于javascript - 将 JSON 对象的字段转换为标题大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30097808/