简体   繁体   English

如何大写 Javascript object 键?

[英]How to uppercase Javascript object keys?

Anyone know a good way to turn this?:任何人都知道一个很好的方法来改变这个?:

var obj = [{key1: value1,key2: value2},{key3: value3,key4: value4}];

into:进入:

var obj = [{Key1: value1,Key2: value2},{Key3: value3,Key4: value4}];

Loop through delete and replace:循环删除和替换:

var obj = [{key1: 1,key2: 1},{key3: 1,key4: 1}];
for(var i = 0; i<obj.length;i++) {

    var a = obj[i];
    for (var key in a) {
        if (a.hasOwnProperty(key)) {
          a[key.charAt(0).toUpperCase() + key.substring(1)] = a[key];
          delete a[key];
          
        }
    }
    obj[i] = a;

}

As of 2019 you can use Object.fromEntries :截至 2019 年,您可以使用Object.fromEntries

 let populations = {london: 8.9, beijing: 21.54, mumbai: 18.41}; // March 2020 let entries = Object.entries(populations); let capsEntries = entries.map((entry) => [entry[0][0].toUpperCase() + entry[0].slice(1), entry[1]]); let capsPopulations = Object.fromEntries(capsEntries); console.log(capsPopulations);

    const transform = (arrObj) => {
    let newObj=[];
    for(let obj of arrObj) {
      let temp=new Object();
      let keys = Object.keys(obj);
      let values = Object.values(obj);
      let i=0;
      keys.forEach(key => {
          key=key[0].toUpperCase() + key.slice(1);
          temp[`${key}`]=values[i++];
      });
      newObj.push(temp);
    }
    return newObj;
  };
  const arrObj = [{first: 'satya', last:'prakash'}, {college: 'AIT'}];
  console.log(transform(arrObj));
  

If you need to capitalize just first letter you can go with Jeremiah's answer如果您只需要大写第一个字母,您可以使用Jeremiah 的答案

or if you need to capitalize first letter of each word consider the following或者如果您需要将每个单词的首字母大写,请考虑以下内容

 let populations = {"london": 8.9, "beijing": 21.54, "mumbai": 18.41, "new york": 19.4}; let entries = Object.entries(populations); // Capitalize first letter of each word let capsEntries = entries.map((entry) => [entry[0].replace(/(^\\w{1})|(\\s+\\w{1})/g, letter => letter.toUpperCase()), entry[1]]); let capsPopulations = Object.fromEntries(capsEntries); console.log(capsPopulations)

Regex adopted from this answer这个答案中采用的正则表达式

Regex Explanation :正则表达式说明

  1. (^\\w{1}) : match first char of string (^\\w{1}) : 匹配字符串的第一个字符
  2. | : or : 要么
  3. (\\s{1}\\w{1}) : match one char that came after one space (\\s{1}\\w{1}) : 匹配一个空格后的一个字符
  4. g : match all g : 匹配所有
  5. match => match.toUpperCase(): replace with can take function, so; match => match.toUpperCase(): 替换为 can take 函数,所以; replace match with upper case match用大写匹配替换匹配

Another approach (more clean)另一种方法(更干净)

import * as _ from 'lodash'; import * as _ from 'lodash';

function capitalizeObjectKeys(obj) { return _.transform(obj, (result, val, key) => { result[key.charAt(0).toUpperCase() + key.slice(1)] = val; }); function capitalizeObjectKeys(obj) { return _.transform(obj, (result, val, key) => { result[key.charAt(0).toUpperCase() + key.slice(1)] = val; }); } }

https://stackblitz.com/edit/js-hsqutg?embed=1&file=index.js https://stackblitz.com/edit/js-hsqutg?embed=1&file=index.js

In my case this code worked well.就我而言,这段代码运行良好。 Both in uppercase and lowercase with map:大写和小写都带有地图:

to uppercase :大写:

 const newDataUpperCase = data.map( function( item ){ for(var key in item){ var upper = key.toUpperCase(); if( upper !== key ){ item[ upper ] = item; delete item[key]; } } return item; });

to lowercase :小写:

 const newDataUpperCase = data.map( function( item ){ for(var key in item){ var lower= key.toLowerCase(); if( lower!== key ){ item[ lower] = item; delete item[key]; } } return item; });

This will help you:这将帮助您:

const griddata = [
  {
      "id_pk": 238,
      "acT_ID": 238,
      "desc": "Record 2",
      "parent": 0,
      "compdays": 5,
      "logical": "1",
      "quantity": "1",
      "lisT_ID": 75,
      "empL_ID": 1388,
      "default": 8,
      "level": "0",
      "sortorder": 2,
      "vfpRecNo": 0,
      "isDeleted": false,
      "clientID": 1,
      "empl_num": "1388",
      "duedate": "05/04/2022"
  }
]

const upperCaseKeys = (data) => {
    debugger;
    let gridData = [];
    if (data != null && data != undefined && data.length > 0) {
      let keys = Object.keys(data[0]);
      let upperCaseKey = [];

      for (let j = 0; j < data.length; j++) {
        upperCaseKey = [];
        for (let i = 0; i < keys.length; i++) {
          set(upperCaseKey, keys[i].toUpperCase(), data[j][keys[i]]);
        }
        upperCaseKey.push(...upperCaseKey);

        gridData.push(Object.assign({}, upperCaseKey));
      }
    }
    console.log("upperCaseKeys",gridData)
  }

const set = (obj, prop, value) => {
    obj[prop] = value;
}

upperCaseKeys(griddata)

Output: Output:

upperCaseKeys [
  {
    ID_PK: 238,
    ACT_ID: 238,
    DESC: 'Record 2',
    PARENT: 0,
    COMPDAYS: 5,
    LOGICAL: '1',
    QUANTITY: '1',
    LIST_ID: 75,
    EMPL_ID: 1388,
    DEFAULT: 8,
    LEVEL: '0',
    SORTORDER: 2,
    VFPRECNO: 0,
    ISDELETED: false,
    CLIENTID: 1,
    EMPL_NUM: '1388',
    DUEDATE: '05/04/2022'
  }
]

使用 lodash 的 _.capitalize 函数

_.capitalize('firstName') => FirstName

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

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