简体   繁体   English

更改 JavaScript 对象键的大小写

[英]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",
  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我希望能够访问这样的值: - obj[0].ADDRESS1

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/ http://jsfiddle.net/07xortqy/

  1. Loop over all the properties in the object (with for in )循环遍历对象中的所有属性(使用for in
  2. Use .toUpperCase() to get the uppercase version of the property name使用.toUpperCase()获取属性名称的大写版本
  3. Copy the value from the original property to the uppercase version将值从原始属性复制到大写版本
  4. delete the original property delete原来的属性

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.您现在还可以将Object.fromEntries()Object.entries()结合使用 - 请查看对象转换部分。

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/ https://jsfiddle.net/buj5y32x/3/

For wider support, you are better off using Object.keys() with Array.reduce() .为了获得更广泛的支持,最好将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/ 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]; 
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM