16

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}];
4
  • 3
    Any reason you'd want to do this? Any code which is using the old keys will break, because keys are case sensitive. Commented Sep 13, 2011 at 21:19
  • Are you looking for a regex or a way to do it while the code is running? Commented Sep 13, 2011 at 22:02
  • 1
    @Marc B, I very well might choose to do this if, for instance, I'm making jqgrids and the column names have a capitalized first letter. Then say I'm getting json back from an existing API and the keys actually have to match case so the jqgrid will function properly. In this case, I would want to guarantee that the keys I'm getting from the json have an uppercase first letter as well and ergo, match. Commented Sep 14, 2011 at 15:17
  • @tjameson, given the frequency of which I have to perform this operation, speed is not a bottleneck so I would say whatever function works including a regex. Commented Sep 14, 2011 at 15:19

8 Answers 8

21

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;

}
Sign up to request clarification or add additional context in comments.

4 Comments

+1, but note if the starting object contains both a lowercase and initial-caps version of a particular keyname then the latter will be overwritten. I.e., {key1:1, Key1:2} will end up as {Key1:1}. (Also, the obj[i] = a; after the for is redundant isn't it?)
The only difference is that I used slice instead of substring. Otherwise, this is excellent.
You can delete the original property (a[key]) after you set the new property, and then you won't need the temp variable.
Object.keys(a).forEach((key) => { a[key.charAt(0).toUpperCase() + key.substring(1)] = a[key]; delete a[key]; });
9

As of 2019 you can use 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);

1 Comment

You can also use destructuring here: entries .map (([k, v]) => [k [0] .toUpperCase () + k .slice (1), v]).
4

Another approach (more clean)

import * as _ from 'lodash';


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

Comments

1

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;
    });

Comments

1

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:

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'
  }
]

Comments

0
    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));
  

Comments

0

If you need to capitalize just first letter you can go with Jeremiah's answer

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
  2. |: or
  3. (\s{1}\w{1}): match one char that came after one space
  4. g: match all
  5. match => match.toUpperCase(): replace with can take function, so; replace match with upper case match

Comments

-5

use lodash's _.capitalize function

_.capitalize('firstName') => FirstName

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.