更改JavaScript对象键的大小写

时间:2014-10-29 11:29:00

标签: javascript

我有以下对象。

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

如何将所有键设为大写?

我希望能够访问以下值: - obj[0].ADDRESS1

8 个答案:

答案 0 :(得分:7)

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 :(得分:5)

  1. 遍历对象中的所有属性(使用for in
  2. 使用.toUpperCase()获取属性名称的大写版本
  3. 将值从原始属性复制到大写版本
  4. delete原始财产

答案 2 :(得分:1)

对于寻找使用对象,数组和嵌套对象或数组的解决方案的任何人:

// 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)))

(这个函数需要改编,因为我只需要将第一个字母大写,并且不需要嵌套辅助函数)

答案 3 :(得分:0)

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

答案 4 :(得分:0)

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)

答案 5 :(得分:0)

您现在还可以将Object.fromEntries()Object.entries()结合使用-看一下Object transformations部分。

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

我已经详细说明了以下步骤:

// 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/

答案 6 :(得分:0)

要获得更广泛的支持,最好将Object.keys()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/

答案 7 :(得分:-2)

您可以循环浏览它们并添加新条目吗?

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