Skip to content
Advertisement

How to uppercase Javascript object keys?

Anyone know a good way to turn this?:

var obj = [{key1: value1,key2: value2},{key3: value3,key4: value4}];

into:

var obj = [{Key1: value1,Key2: value2},{Key3: value3,Key4: value4}];

Advertisement

Answer

Loop through delete and replace:

var obj = [{key1: 1,key2: 1},{key3: 1,key4: 1}];
for(var i = 0; i<obj.length;i++) {

    var a = obj[i];
    for (var key in a) {
        if (a.hasOwnProperty(key)) {
          a[key.charAt(0).toUpperCase() + key.substring(1)] = a[key];
          delete a[key];
          
        }
    }
    obj[i] = a;

}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement