Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the case of JavaScript object keys

Tags:

javascript

I have following object.

var obj = [{
  Address1: "dd",
  Address2: "qww",
  BankAccNo: "44",
  BankBranchCode: "44",
  BloodGrp: "A+"
},
{
  Address1: "dd",
  Address2: "qww",
  BankAccNo: "44",
  BankBranchCode: "44",
  BloodGrp: "A+"
}];

How can I make all of the keys uppercase?

I want to be able to access values like this : - obj[0].ADDRESS1

like image 981
Anup Avatar asked Oct 29 '14 11:10

Anup


People also ask

How do you change the key of an object JavaScript?

To rename a key in an object:Use bracket notation to assign the value of the old key to the new key. Use the delete operator to delete the old key. The object will contain only the key with the new name.

Is JavaScript object key case sensitive?

JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters. The while keyword, for example, must be typed “while”, not “While” or “WHILE”.

How do I change the key-value of a object?

To update all the values in an object:Use the Object. keys() method to get an array of the object's keys. Iterate over the array using the forEach() method and update each value. After the last iteration, all the values in the object will be updated.

Can JavaScript object have same keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.


2 Answers

obj = obj.map( function( item ){
    for(var key in item){
        var upper = key.toUpperCase();
        // check if it already wasn't uppercase
        if( upper !== key ){ 
            item[ upper ] = item[key];
            delete item[key];
        }
    }
    return item;
});

http://jsfiddle.net/07xortqy/

like image 99
pawel Avatar answered Oct 10 '22 01:10

pawel


  1. Loop over all the properties in the object (with for in)
  2. Use .toUpperCase() to get the uppercase version of the property name
  3. Copy the value from the original property to the uppercase version
  4. delete the original property
like image 45
Quentin Avatar answered Oct 09 '22 23:10

Quentin