Ways to convert all keys to uppercase in an array of objects?

Is there a way to capitalize the first letter of every key in an array of objects? I attempted to achieve this with the code below, but it's not working as expected.

Any suggestions or corrections are appreciated. #current code

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

#sample object

  [{
        "id": 3,
        "accountId": 6,
        "title": "ABCDF Copy",
        "versionDto": {
            "id": 3,
            "entitlementsTemplateId": 3,
            "status": "Draft",
            "entitlementElementsTemplateDto": [
                {
                    "id": 5,
                    "isHeaderCategory": false,
                    "order": 1,
                },
        {
                    "id": 6,
                    "isHeaderCategory": false,
                    "order": 2,
                }

            ]
        }
    }]

#expected output

[{
    "Id": 3,
    "AccountId": 6,
    "Title": "ABCDF Copy",
    "VersionDto": {
        "Id": 3,
        "EntitlementsTemplateId": 3,
        "Status": "Draft",
        "EntitlementElementsTemplateDto": [
            {
                "Id": 5,
                "IsHeaderCategory": false,
                "Order": 1,
            },
            {
                "Id": 2,
                "IsHeaderCategory": false,
                "Order": 2,
            }

        ]
    }
}]

Answer №1

Let's recursively iterate through the entire object using Object.keys(obj)

const transformKeys = (obj) => {
  if (!obj) {
    return;
  }
  Object.keys(obj).forEach(key => {
    var value = obj[key]
    if (typeof value === "object" && value !== null) {
      transformKeys(value)
    }
    var Key = key[0].toUpperCase() + key.substr(1);
    delete obj[key];
    obj[Key] = value;
  })
}

var obj = [{
  "id": 3,
  "accountId": 6,
  "title": "ABCDF Copy",
  "versionDto": {
    "id": 3,
    "entitlementsTemplateId": 3,
    "status": "Draft",
    "entitlementElementsTemplateDto": [{
        "id": 5,
        "isHeaderCategory": false,
        "order": 1,
      },
      {
        "id": 6,
        "isHeaderCategory": false,
        "order": 2,
      }

    ]
  }
}]


var object2 = {
  "id": 2,
  "accountId": 6,
  "title": "TEMPLATE 2",
  "entitlementsTemplateVersionDto": {
    "id": 2,
    "entitlementsTemplateId": 2,
    "status": "Draft",
    "entitlementElementsTemplateDto": [{
        "id": 2,
        "entitlementsTemplateVersionId": 2,
        "entitlementName": "TEMPLATE C",
        "isHeaderCategory": true,
        "order": 1,
        "isRequired": false,
        "entitlementSubCategoryElementsTemplateDto": [{
            "id": 1,
            "entitlementElementsTemplateId": 2,
            "entitlementName": "",
            "order": 0,
            "isRequired": false
          },
          {
            "id": 2,
            "entitlementElementsTemplateId": 2,
            "entitlementName": "",
            "order": 0,
            "isRequired": false
          }
        ]
      },
      {
        "id": 3,
        "entitlementsTemplateVersionId": 2,
        "entitlementName": "TEMPLATE B",
        "isHeaderCategory": false,
        "order": 1,
        "isRequired": false,
        "entitlementSubCategoryElementsTemplateDto": []
      },
      {
        "id": 4,
        "entitlementsTemplateVersionId": 2,
        "entitlementName": "TEMPLATE A",
        "isHeaderCategory": false,
        "order": 1,
        "isRequired": true,
        "entitlementSubCategoryElementsTemplateDto": []
      }
    ]
  }
}


transformKeys(obj);
console.log(obj)

transformKeys(object2);
console.log(object2)
.as-console-wrapper {
  max-height: 100% !important;
}

Answer №2

It appears that the issue lies in your handling of capitalization.

To resolve this, consider implementing the following approach:

const adjustKeyToCapitalize = (key) => key.charAt(0).toUpperCase() + key.slice(1);

Take a look at this basic demonstration below:

const modifyObjectKeysToCapitalize = (obj) => {
  if (!obj) return;
  if (Array.isArray(obj)) {
    return obj.map((each) => modifyObjectKeysToCapitalize(each))
  }
  const result = {};
  Object.keys(obj).forEach((key) => {
    const newKey = key.charAt(0).toUpperCase() + key.slice(1);
    const objectValue = (typeof obj[key] === 'object') ? modifyObjectKeysToCapitalize(obj[key]) : obj[key];
    result[newKey] = objectValue;
  });
  return result;
};

const example = [{"id":3,"accountId":6,"title":"ABCDF Copy","versionDto":{"id":3,"entitlementsTemplateId":3,"status":"Draft","entitlementElementsTemplateDto":[{"id":5,"isHeaderCategory":false,"order":1},{"id":6,"isHeaderCategory":false,"order":2}]}}];

const updatedObject = modifyObjectKeysToCapitalize(example)

console.log(updatedObject);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When a property is passed as a prop in a Vue component, it is received

https://jsfiddle.net/2xwo87bs/ In order for Vue to properly handle the object prop that is being passed to the component, it is necessary to first convert the string into an actual object. While in the provided snippet I have used JSON.parse() as a qui ...

Issue with knockout view - unable to remove item from view after deletion

I'm facing an issue with my code that deletes an exam from a list of exams on a page, but the deleted exam still shows up until the page is manually refreshed. This pattern works correctly on other pages, so I don't understand why it's not w ...

Trigger modal on designated ID

My code includes a script that assigns a specific id to a button using a variable $i in a for loop: <button id='myBtn$i'>Open Modal</button>. This id should allow me to open specific modals with the corresponding $i value: <div id= ...

Gather data from a variety of HTML5 video seminars

I am encountering an issue where I have multiple videos and I want to receive events from each of them. However, I am only able to get the event from one video (as tested in Chrome). Why is this happening? Here is the HTML code: <video id="video1" pre ...

Is it possible to generate an interactive HTML form using JSON information?

When the user clicks the "get Form" button, a request is sent to the form API to retrieve information for rendering the form. Once the form is rendered, the user can then submit the form. This process can be repeated as needed. HTML: <body ng-app="Json ...

Renewed Promises: Exploring Promises in Angular JS

Revised with HTTP and initial code inspired by requests/Refer to the end of the post: Lately, I have been seeking help from the amazing SO community as I navigate through my AngularJS learning journey. I used to be a traditional C programmer but recently ...

Invoking Ajax Within Every Loop

I am creating dynamic HTML buttons where, upon pressing each button, I want to make an AJAX call to retrieve a value. However, I am encountering an issue where I get as many console outputs as the number of buttons pressed. Here is my PHP code: if(isset($ ...

Utilizing jQuery with variable assignment: A beginner's guide

Struggling to utilize a variable in jQuery? In the script snippet below, I set a variable "divname" with a value, but when using jQuery for fading out, it doesn't work as expected. What I really want is for the description to fade in when hovering ove ...

Child component in VueJs is undergoing a situation where the variable is found to be

Whenever an event is triggered, a function is called to populate a variable and open a modal from a child component. However, in the modal, the new variable appears empty initially. If I close and then reopen the modal, the data finally loads. I have atte ...

Issue with AJAX MVC HTML: jQuery value is not blocking API call

Upon clicking a button, I am triggering a web API call using AJAX. My form is utilizing JqueryVal for form validations based on my viewmodel data annotations. The issue I am facing is that when I click the "Listo" button in my form, it executes the API ca ...

Troubleshooting Problem with Installing Angular2-Google-Maps Component in FountainJS Application

Using the FountainJS Angular2 generator with Typescript and Systems.js has been helpful for scaffolding my project. Check it out here However, I encountered an issue while trying to add a component to the project. Upon importing {GOOGLE_MAPS_DIRECTIVES}, ...

Animating a div in jQuery by creating a duplicate

I've spent hours scouring Google and StackOverflow for a solution to this particular issue I'm facing, but haven't been able to find one. Here's the problem: I'm currently in the process of creating a shopping website. When a user ...

Rearrange element's placement using Jquery Drag & Drop

I am experiencing difficulties in positioning my elements after a drop event. Within my "list" of divs... In order to keep the divs together and update the list, I utilize jQuery's append function to move the element from the list to its designated ...

Having difficulty with pagination within a callback function

I have been attempting to paginate in a call to a callback function, but I am encountering an error on the second call. Here is what my function does: let content = '' let size = 100 let from = 1 function result(size, from, callback) { ap ...

Begin anew with Flip.js

Currently, I am incorporating the jquery flip plugin from nnattawat.github.io/flip to establish a card flipping mechanism on my website. I have successfully implemented the method outlined in the documentation to unregister the flip event from the elemen ...

Implementing ng-if with asynchronous functions: A step-by-step guide

The objective here is to display an image in a template only if the ratio of its dimensions is greater than 2. <img class="main-img" ng-if="showImage($index)" ng-src="{{item.img}}"> Implementation: $scope.showImage = function(index) { var img ...

Removing a specific item from a Kendo UI dropdown list

Recently, I encountered a predicament with a dropdownlist populated from a datasource. Following a certain event, my goal is to eliminate a single item from the dropdownlist identified by id = 22. Although I recognize this may not be the best practice du ...

"Can anyone provide guidance on how to initiate a css 3d animation by clicking a button

Currently, I am developing a folding hide/show animation that can be triggered using Javascript. If you would like to take a look at the code and see a working example, please visit this link: You can also view just the gist here: https://gist.github.com ...

React allows for items to be exchanged between two lists

I am currently working on a functionality that involves swapping items between two arrays. The user interacts with two lists in the UI by selecting items from the first list, which should then be removed from there and added to the second list where the se ...

Can curly braces be utilized in the style section of Vue.js?

Can I utilize curly braces in the style section of vue.js to set a value? For instance .container { background: url({{ image-url }}; color: {{ color-1 }} } ...