Change the keys in an array to uppercase

There is a requirement to convert all keys in an array to uppercase. The user will upload an Excel file where each worksheet is read into separate arrays named check details, ingredients, menu, and desserts.

Current JSON:

[
  [
    "filename",
    "details.xlsx"
  ],
  [
    "Check Details",
    [
      {
        "Outdated Label": "Outdated Label1",
        "Outdated Value": "Outdated Value"
      },
      {
        "Outdated Label": "Outdated Label2",
        "Outdated Value": "Outdated Value2"
      },
      {
        "Outdated Label": "Outdated Label3",
        "Outdated Value": "Outdated Value3"
      },
    {
        "Outdated Label": "Outdated Label4",
        "Outdated Value": "Outdated Value4"
      }
    ]
  ],
  [
    "ingredient",
    [
      {
        "ingredient Id": "1",
        "ingredient Code": "IG01",
        "ingredient Label": "Recipe 1"
      },
      {
        "ingredient Id": "2",
        "ingredient Code": "IG02",
        "ingredient Label": "Secret Recipe"
      },
      {
        "ingredient Id": "4",
        "ingredient Code": "IG04",
        "ingredient Label": "Chef special"
      },
      {
        "ingredient Id": "3",
        "ingredient Code": "IG03",
        "ingredient Label": "Today special"
      }
    ]
  ],
  [
    "menu",
    [
      {
        "Item Menu Id": "M01",
        "Item": "Pizza"
      },
      {
        "Item Menu Id": "M02",
        "Item": "Hotdogs"
      },
       {
        "Item Menu Id": "M03",
        "Item": "French Fries"
      }
    ]
  ],
  [
    "Desserts",
    [
      {
        "Menu Item Id": "DRT01",
        "Item": "Roasted strawberry crumble"
      },
       {
        "Menu Item Id": "DRT01",
        "Item": "Apple and butterscotch pie"
      }
    ]
  ]
  ]

Expected JSON :

[
  [
    "filename",
    "details.xlsx"
  ],
  [
    "Check Details",
    [
      {
        "OUTDATED LABEL": "Outdated Label1",
        "OUTDATED VALUE": "Outdated Value"
      },
      {
        "OUTDATED LABEL": "Outdated Label2",
        "OUTDATED VALUE": "Outdated Value2"
      },
      {
        "OUTDATED LABEL": "Outdated Label3",
        "OUTDATED VALUE": "Outdated Value3"
      },
    {
        "OUTDATED LABEL": "Outdated Label4",
        "OUTDATED VALUE": "Outdated Value4"
      }
    ]
  ],
  [
    "ingredient",
    [
      {
        "INGREDIENT ID": "1",
        "INGREDIENT CODE": "IG01",
        "INGREDIENT LABEL": "Recipe 1"
      },
      {
        "INGREDIENT ID": "2",
        "INGREDIENT CODE": "IG02",
        "INGREDIENT LABEL": "Secret Recipe"
      },
      {
        "INGREDIENT ID": "4",
        "INGREDIENT CODE": "IG04",
        "INGREDIENT LABEL": "Chef special"
      },
      {
        "INGREDIENT ID": "3",
        "INGREDIENT CODE": "IG03",
        "INGREDIENT LABEL": "Today special"
      }
    ]
  ],
  [
    "menu",
    [
      {
        "ITEM MENU ID": "M01",
        "ITEM": "Pizza"
      },
      {
        "ITEM MENU ID": "M02",
        "ITEM": "Hotdogs"
      },
       {
        "ITEM MENU ID": "M03",
        "ITEM": "French Fries"
      }
    ]
  ],
  [
    "Desserts",
    [
      {
        "MENU ITEM ID": "DRT01",
        "ITEM": "Roasted strawberry crumble"
      },
       {
        "MENU ITEM ID": "DRT01",
        "ITEM": "Apple and butterscotch pie"
      }
    ]
  ]
  ]

Note: Key names are dynamic as they can be anything based on the Excel upload.

Answer №2

This code snippet efficiently transforms the keys of objects in an array, recursively and in place.

  input = "your JSON input"

  data: any[] = [];

  output = '';

  ngOnInit(): void {
    this.data = JSON.parse(this.input);
    this.traverseArray(this.data);
    this.output = JSON.stringify(this.data);
  }

  traverseArray(arr: any[]) {
    for (const item of arr) {
      if (item instanceof Array) this.traverseArray(item);
      else if (item instanceof Object) this.convertKeysToUpperCase(item);
    }
  }

  convertKeysToUpperCase(obj: any) {
    for (const key of Object.keys(obj)) {
      Object.assign(obj, { [key.toUpperCase()]: obj[key] });
      delete obj[key];
    }
  }

Try it on Stackblitz: https://stackblitz.com/edit/angular-ivy-zrjp5k?file=src/app/app.component.ts

Please note: This implementation assumes there are no nested arrays or objects within another object.

Answer №3

In order to restructure an array and rename the keys, recursion can be utilized as shown below:

var originalArray = [ [ "filename", "details.xlsx" ], [ "Check Details", [ { "Outdated Label": "Outdated Label1", "Outdated Value": "Outdated Value" }, { "Outdated Label": "Outdated Label2", "Outdated Value": "Outdated Value2" }, { "Outdated Label": "Outdated Label3", "Outdated Value": "Outdated Value3" }, { "Outdated Label": "Outdated Label4", "Outdated Value": "Outdated Value4" } ] ], [ "ingredient", [ { "ingredient Id": "1", "ingredient Code": "IG01", "ingredient Label": "Recipe 1" }, { "ingredient Id": "2", "ingredient Code": "IG02", "ingredient Label": "Secret Recipe" }, { "ingredient Id": "4", "ingredient Code": "IG04", "ingredient Label": "Chef special" }, { "ingredient Id": "3", "ingredient Code": "IG03", "ingredient Label": "Today special" } ] ], [ "menu", [ { "Item Menu Id": "M01", "Item": "Pizza" }, { "Item Menu Id": "M02", "Item": "Hotdogs" }, { "Item Menu Id": "M03", "Item": "French Fries" } ] ], [ "Desserts", [ { "Menu Item Id": "DRT01", "Item": "Roasted strawberry crumble" }, { "Menu Item Id": "DRT01", "Item": "Apple and butterscotch pie" } ] ] ]
var deepLoop = function(inputArray){

    /* Re-map the input array, input array will change based on recursion call */
    inputArray.map(function(item){

        /* If current iteration is an array, call the recursion until we reach an object */
        if(Array.isArray(item)){
            deepLoop(item);
        }
        else if(typeof item === "object"){
            /* This is an object, update the keys */
            Object.keys(item).forEach(function(key){
                /* Rename key, solution from => https://stackoverflow.com/questions/4647817/javascript-object-rename-key */
                Object.defineProperty(item, key.toUpperCase(),
                Object.getOwnPropertyDescriptor(item, key));
                delete item[key];
                
            });
            
        }
        return item;
    });
};

/* First Call */
deepLoop(originalArray);

console.log("Updated Array => ", originalArray);

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

I encountered an issue with uploading an image file in Angular and am currently experiencing an error

media.components.html <div class="row justify-content-center" style="position:relative;top:105px;"> <div class="col-md-6"> <!-- form company info --> <div class="card card-outline-secondary"> <div ...

Navigating with multiple parameters in Angular 7 routing

I am currently facing an issue where I need to navigate to the same component with different parameters. Although I can subscribe to the params through the ActivatedRoute, I'm encountering a problem when trying to call router.navigate within the subsc ...

What is the best method for encrypting a file using node.js?

I am in the process of finding a way to encrypt various types of files like txt, mp3, or any other file in node.js while utilizing socket.io. My goal is to develop an application that can securely send files to another client, so I wish to encrypt the file ...

What is the best way to retrieve data from a server and display it using Highcharts in Angular 2

This is my chart component and I am trying to display a chart with values from the server. Unfortunately, it's not working even though it works with static values. In the ngOnInit method, I call the web service and store the data in a variable called ...

Using sl-vue-tree with vue-cli3.1 on internet explorer 11

Hello, I am a Japanese individual and my proficiency in English is lacking, so please bear with me. Currently, I am using vue-cli3.1 and I am looking to incorporate the sl-vue-tree module into my project for compatibility with ie11. The documentation menti ...

Content that can be scrolled in Angular2

After using Perfect Scrollbar, I transitioned to Angular 2 and now I am struggling to find a similar solution. How can I properly add Perfect Scrollbar to my Angular 2 project? I tried following an example from this informative resource, however I am unsu ...

Utilizing Knockout to Load JSON Data in DevExtreme

As a newcomer to both javascript and devextreme, I am currently navigating my way through. I successfully created a webpage that loads a json file, but I'm facing challenges implementing it using devextreme. I have a dxDataGrid where I intend to disp ...

"Using routerLink will attach my specified URL to the anchor tag

On all pages, I have implemented a menu navigation component with the following links: - Following - Followers When I visit http://localhost/#/, the links are generated correctly: - http://localhost/#/network;scrollTo=%23Following - http://localh ...

Issue with table display within <div> element in React

Recently diving into React, I find myself in a situation where I need to display data in a table once it's ready or show 'Loading' if not. Currently, my render() function looks like this: return ( <div> { this.state.loaded ...

Exploring Typescript and Clean Architecture with an In-Memory Database/Repository

Currently, I am integrating clean architecture in my latest project and facing challenges with repositories, data sources, and terminology. My aim is to test my useCases using an in-memory repository as I am only concerned about the business logic at this ...

Migration of information from MySQL to javascript

I recently started learning about MySQL and I'm exploring ways to transfer data from a MySQL table to JavaScript. My goal is to create a multidimensional array in JavaScript using the data from the MySQL table, which will then be utilized in other fun ...

Is 'get Some(): Todo[] {}' some sort of abbreviated method?

While going through an Angular services tutorial, I stumbled upon some code snippet. fetchData(): Data[] { return [ { label: "Data 1", type: DataType.INTEGER }, { label: "Data 2", type: DataType.STRING }, { label: "Data 3", type: DataType.BO ...

Using script tags incorrectly (JavaScript platform game)

Currently, I am working on the 'create a platform game' project as outlined in Eloquent JavaScript, and I have encountered an issue related to script tags. As per the instructions in the book, we are advised to showcase our level using: <lin ...

Adding a new div using Jquery after a specific table row

I am having trouble displaying additional data in a table when a specific row is clicked. Here is the table structure I am working with: <div id="display"> <div class="displayRow"> <img src="images/expand-arrow.gif" class="expandArrow ...

Exploring the Contrast between Application and Local State Management in Redux

When looking at various examples of Redux, actions like SOME_ASYNC_ACTION_ERROR and SOME_ASYNC_PENDING are commonly used to manipulate the global state. However, it is hard to imagine a scenario where it would be logical for a component to be initially ren ...

Tips on adding an item to an array with React hooks and TypeScript

I'm a beginner with a simple question, so please bear with me. I'm trying to understand how to add an Object to the state array when a form is submitted. Thank you for your help! interface newList { name: string; } const ListAdder = () => { ...

What is the best method to utilize angular 2 cli for copying css and essential files to the dist folder?

After setting up my Angular 2 TypeScript solution and including the material Angular 2 npm package, I followed these steps: npm install -g angular-cli ng new PROJECT_NAME cd PROJECT_NAME ng build The files were successfully transferred from my source fol ...

Tips for assigning custom values using CSS and jQuery for a standalone look

I am facing a challenge with my HTML markup: <div> <figure></figure> <figure></figure> <figure></figure> </div> Alongside some CSS styling: div { position: relative; } figure { position: absolu ...

Change values within nested observables

fetchingData() { return this.http.get(environment.remoteUrl + '/client').pipe(pluck('rows'), map((item: any) => item.doc)); } The data is structured like this: { rows: [ {x: 123, doc: {a: 2}}, {x:222, doc: {a: ...

How to ensure that the $window.location.reload(true) function is executed only once in an Ionic/Angular application

I need help modifying this code so that it resets my app only once when it goes to the homepage instead of continuously reloading. What changes can I make in the JavaScript to achieve this? .controller('HomeCtrl', function ($scope, $window) { $s ...