Changing the case of JavaScript object keys

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/


  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

For anyone looking for a solution working with objects, arrays, and nested objects or arrays:

// rename function depending on your needs
const capitalizeKeys = (obj) => {
  const isObject = o => Object.prototype.toString.apply(o) === '[object Object]'
  const isArray = o => Object.prototype.toString.apply(o) === '[object Array]'
  
  let transformedObj = isArray(obj) ? [] : {}
  
  for (let key in obj) {
    // replace the following with any transform function
    const transformedKey = key.replace(/^\w/, (c, _) => c.toUpperCase())

    if (isObject(obj[key]) || isArray(obj[key])) {
      transformedObj[transformedKey] = capitalizeKeys(obj[key])
    } else {
      transformedObj[transformedKey] = obj[key]
    }
  }
  return transformedObj
}

const t = {
  test1: 'hello',
  test2: {
    aa: 0,
    bb: '1',
    cc: [ 3, '4', 'world']
  },
  test3: [{
      aa: 5,
      bb: '6'
    }, {
      cc: [ 'hello', 'world', 7 ]
    }
  ]
}

console.log(JSON.stringify(capitalizeKeys(t)))

(this function is to be adapted since I only had to capitalize the first letter, and there is no need for the helper functions to be nested)

Tags:

Javascript