Convert returned JSON Object Properties to (lower first) camelCase

后端 未结 18 2329
忘掉有多难
忘掉有多难 2020-12-04 21:05

I have JSON returned from an API like so:

Contacts: [{ GivenName: "Matt", FamilyName: "Berry" }]

To keep this consistent

18条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 21:42

    Well I took up the challenge and think I figured it out:

    var firstToLower = function(str) {
        return str.charAt(0).toLowerCase() + str.slice(1);
    };
    
    var firstToUpper = function(str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
    };
    
    var mapToJsObject = function(o) {
        var r = {};
        $.map(o, function(item, index) {
            r[firstToLower(index)] = o[index];
        });
        return r;
    };
    
    var mapFromJsObject = function(o) {
        var r = {};
        $.map(o, function(item, index) {
            r[firstToUpper(index)] = o[index];
        });
        return r;
    };
    
    
    // Map to
    var contacts = [
        {
            GivenName: "Matt",
            FamilyName: "Berry"
        },
        {
            GivenName: "Josh",
            FamilyName: "Berry"
        },
        {
            GivenName: "Thomas",
            FamilyName: "Berry"
        }
    ];
    
    var mappedContacts = [];
    
    $.map(contacts, function(item) {
        var m = mapToJsObject(item);
        mappedContacts.push(m);
    });
    
    alert(mappedContacts[0].givenName);
    
    
    // Map from
    var unmappedContacts = [];
    
    $.map(mappedContacts, function(item) {
        var m = mapFromJsObject(item);
        unmappedContacts.push(m);
    });
    
    alert(unmappedContacts[0].GivenName);
    

    Property converter (jsfiddle)

    The trick is handling the objects as arrays of object properties.

提交回复
热议问题