Coloco
Coloco

Reputation: 353

Converting a JSON object's fields into Title Case

I have a JSON object I get from a database (using Slim and Twig) but there's a field that is sometimes in upper case, sometimes in lower case, sometimes in camelCase, etc. I'd like that this field becomes TitleCase.

I already have a function to convert a String to TitleCase, which I have used when converting JSON to arrays (using these arrays as sources for jqWidgets) :

function toTitleCase(str) {
    return str.replace(/\w\S*/g, function (txt) {return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
}

Now I'd like to do the same thing for JSON objects. What I thought of is to iterate over them after using parseJSON(), use my function on the fields I want and return new objects after using JSON.stringify(); but I'm wondering if you think this is the best approach to this problem or if you have a better idea (I'm not asking for direct source code).

Example of my JSON (I need nomFonction and nomEntite in TitleCase) :

"[{"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"}]"

Upvotes: 0

Views: 2242

Answers (1)

Coloco
Coloco

Reputation: 353

So, I did what I wanted to do which is iterating over the JSON object converted to an Array and convert it back to JSON.

Code :

// 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);
}

Usage :

JSONToTitleCase(JSON_Array, fieldtoconvert1, fieldtoconvert2, ...);

In my case :

JSONToTitleCase(fonctionsEnBase, "nomEntite", "nomFonction");

Upvotes: 1

Related Questions