Skip to content Skip to sidebar Skip to footer

Changing The Case Of Javascript Object Keys

I have following object. var obj = [{ Address1: 'dd', Address2: 'qww', BankAccNo: '44', BankBranchCode: '44', BloodGrp: 'A+' }, { Address1: 'dd', Address2: 'qww', B

Solution 1:

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

http://jsfiddle.net/07xortqy/

Solution 2:

  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

Solution 3:

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

// rename function depending on your needsconstcapitalizeKeys = (obj) => {
  constisObject = o => Object.prototype.toString.apply(o) === '[object Object]'constisArray = o => Object.prototype.toString.apply(o) === '[object Array]'let transformedObj = isArray(obj) ? [] : {}
  
  for (let key in obj) {
    // replace the following with any transform functionconst 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)

Solution 4:

$.each(obj, function(i, parent) {
  $.each(parent, function(key, record) {
    parent[ key.toUpperCase() ] = record[key]; //rename keydelete parent[key]; //delete old key
  });
});

Solution 5:

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

constuppercaseKeys = (elem) => {
  let newObject = {}

  Object.keys(elem).reduce( (acc, key, allKeys) => {
    acc[key.toUpperCase()] = elem[key]
    delete elem[key]
    return acc
  }, elem)

  return newObject
}

obj.forEach( o => uppercaseKeys )
console.log(obj)

Post a Comment for "Changing The Case Of Javascript Object Keys"