admin管理员组

文章数量:1186686

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

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

Share Improve this question edited Oct 29, 2014 at 11:39 nbrooks 18.2k5 gold badges56 silver badges67 bronze badges asked Oct 29, 2014 at 11:29 AnupAnup 9,72817 gold badges77 silver badges145 bronze badges 4
  • 1 Why not just access them as they are? – nnnnnn Commented Oct 29, 2014 at 11:33
  • @nnnnnn maybe because of consistency with some DB name fields, just guessing – A. Wolff Commented Oct 29, 2014 at 11:40
  • Yes...I am matching this keys with values stored in DB, which are in Uppercase.! – Anup Commented Oct 29, 2014 at 11:43
  • if your js object has hierarchal structure and you want to capitalize only a specific object, jsfiddle.net/72q0ed6z/7 – M Alok Commented Jun 9, 2023 at 5:01
Add a comment  | 

8 Answers 8

Reset to default 12
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)

$.each(obj, function(i, parent) {
  $.each(parent, function(key, record) {
    parent[ key.toUpperCase() ] = record[key]; //rename key
    delete parent[key]; //delete old key
  });
});
let obj = [
{ Address1: "dd",Address2: 'qww',BankAccNo: 44,BankBranchCode: 44,BloodGrp: 'A+' },
{ Address1: "dd",Address2: 'qww',BankAccNo: 44,BankBranchCode: 44,BloodGrp: 'A+' }
];

const uppercaseKeys = (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)

You can now also use Object.fromEntries() in combination with Object.entries() - have a look at the Object transformations section.

const obj2 = obj1.map(item => Object.fromEntries(Object.entries(item).map(([key, val]) => [
  key.toUpperCase(),
  val
])));

I've detailed the steps below:

// Iterate through each item in array
const obj2 = obj1.map(item => {
  // Object.entries() method returns array of object's own enumerable string-keyed property [key, value] pairs, 
  // in the same order as that provided by a for...in loop
  const entries = Object.entries(item);

  // Convert keys to uppercase
  const uppercaseEntries = entries.map(([key, val]) => [
    key.toUpperCase(),
    val
  ]);

  // Object.fromEntries() method transforms a list of key-value pairs into an object.
  return Object.fromEntries(uppercaseEntries);
});`

https://jsfiddle.net/buj5y32x/3/

For wider support, you are better off using Object.keys() with Array.reduce().

const obj2 = obj1.map(item =>
  Object.keys(item).reduce((accumulator, key) => {
    // accumulator is the new object we are creating
    accumulator[key.toUpperCase()] = item[key];
    return accumulator;
  }, {})
);

https://jsfiddle.net/qf81ezsy/

You could just loop through them and add new entries?

for (index in obj) {
  for (key in obj[index]) { 
     obj[index][key.toUpperCase()] = obj[key]; 
  }
}

本文标签: Changing the case of JavaScript object keysStack Overflow