bagya bagya - 4 months ago 20
AngularJS Question

How to transform all JSON keys to lowercase in javascript?

Actually, my requirement is to convert whole JSON(only keys) into lowercase. I tried it's converting only first key of that JSON and it's not converting whole all key. Please have a look the fiddle link or please provide any other ways to do this.

Thanks...

var obj = {
"Collections": {
"conTainer": {
"rowSet": [{
"containerIsArchived": "Null",
"containerOrderNo": "26",
"versionNum": "0",
"containerGlobalUniqueId": "Null",
"containerIsTenantBased": "true",
"containerCreatedBy": "user",
"containerIsDeleted": "false",
"containerTenantId": "292FEC76-5F1C-486F-85A5-09D88096F098",
"containerLayoutId": "4e13dfcd-cd3b-4a29-81bd-0f73cf9577cf",
"containerApplicationId": "0000000-0000-0000-0000-000000000000",
"containerIsActive": "Null",
"containerHeaderText": "apitest19feb16",
"containerId": "3745b273-c48d-4c94-b576-3d7aac2f7ac6",
"containerCreatedUTCDate": "2016-02-19 17:57:51.0"
}]
}
}
};

convertKeysToCamelCase(obj);

function convertKeysToCamelCase(obj) {
if (!obj || typeof obj !== "object") return null;

if (obj instanceof Array) {
return $.map(obj, function(value) {
return convertKeysToCamelCase(value);
});
}

var newObj = {};
$.each(obj, function(key, value) {
key = key.charAt(0).toLowerCase() + key.slice(1);
newObj[key] = value;
});
console.log(newObj);
return newObj;
};


Here the Fiddle link: fiddle

Answer

Try the below code

function ConvertKeysToLowerCase(obj) {
    var output = {};
    for (i in obj) {
        if (Object.prototype.toString.apply(obj[i]) === '[object Object]') {
           output[i.toLowerCase()] = ConvertKeysToLowerCase(obj[i]);
        }else if(Object.prototype.toString.apply(obj[i]) === '[object Array]'){
            output[i.toLowerCase()]=[];
             output[i.toLowerCase()].push(ConvertKeysToLowerCase(obj[i][0]));
        } else {
            output[i.toLowerCase()] = obj[i];
        }
    }
    return output;
};

JsFiddle

Comments