What is the best way to eliminate square brackets from keys within an array of objects in TypeScript?

I am currently working on a task to eliminate all square brackets from the keys in the entries field within an array of objects:

data: [
   {title: "Title1", entries: { 'Entry1': 333333, '[ABC]Entry2': 1234, 'Entry3': 5555 }}, 
   {title: "Title2", entries: { '[ABC]Entry1': 5555, 'Entry2': 4444,'Entry3': 2222 }}
]

The objective is to transform [ABC]Entry2 and [ABC]Entry1 into ABCEntry2 and ABCEntry1, respectively.

To achieve this, I have iterated through the data array and then looped over the keys using Object.keys(x.entries). Within that loop, I check for any existing brackets in the key, and if found, replace them with an empty string.

Below is the code snippet depicting this logic:

data.map(x => {
   Object.keys(x.entries).map( y => {
      if(y.includes('[') && y.includes(']')) {
         y = y.replace(/\[/g, '').replace(/]/g, '');
         console.log("The updated key without brackets: ", y);
      }
   })
   console.log("Entries with brackets still present: ", x.entries);         
})

console.log("Original data still containing brackets: ", data);  

Although the console displays the desired result without square brackets when printing the y value inside the loop, it reverts back to the original data structure outside the loop. Is there a way to directly update x.entries and reflect these changes in data without creating a new variable to store the modifications?

Answer №1

Modifying the value of y within the callback function does not alter the original object. Instead, you can remap the key to a new key and then create a fresh object using the remapped entries.

const data=[{title:"Title1",entries:{'Entry1':333333,'[ABC]Entry2':1234,'Entry3':5555}},{title:"Title2",entries:{'[ABC]Entry1':5555,'Entry2':4444,'Entry3':2222}}];

const newData = data.map((object) => ({
    ...object,
    entries: Object.fromEntries(Object.entries(object.entries)
        .map(([key, value]) => [
            key.replace(/\[/g, "").replace(/\]/g, ""),
            value,
        ])),
}));

console.log(newData);


If you want to change the original data array directly, you can iterate over the keys, generate a new key, delete the old key, and then assign the new one.

const data=[{title:"Title1",entries:{'Entry1':333333,'[ABC]Entry2':1234,'Entry3':5555}},{title:"Title2",entries:{'[ABC]Entry1':5555,'Entry2':4444,'Entry3':2222}}];

data.forEach((object) => {
    for (const key in object.entries) {
        const newKey = key.replace(/\[/g, "").replace(/\]/g, "");
        const value = object.entries[key];
        
        delete object.entries[key];
        
        object.entries[newKey] = value;
    }
});

console.log(data);

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

Tips for preventing the error message "The property 'map' is not present on type 'string | string[]'."

I received an error message stating Property 'map' does not exist on type 'string | string[]': const data = [ ['1', ['11']], ['2', ['21']], ['3', ['31']], ] data.map(top ...

Is there a way to denote a specific part of a generic type without explicitly specifying the parts as generics themselves?

My dilemma involves an object defined by a type from a 3rd party library: // Unable to modify this - it belongs to the 3rd party library; interface TypedEvent< TArgsArray extends Array<any> = any, TArgsObject = any > extends Event { args ...

Modify the empty message for the PrimeNG multiselect component

Is there a way to customize the message 'no results found' in p-multiselect on Angular? I have successfully changed the default label, but I am struggling to find a solution to override the empty message. Here is my code snippet: <p-multiSel ...

Guidelines for forming a composite type with elements?

Imagine having a convenient function that wraps a generic component with a specified constant. function wrapComponent(ComponentVariant: ComponentVariantType) { return ( <Wrapper> <ComponentVariant> <InnerComponent /> ...

RC7 is missing the necessary HTTP_PROVIDERS for the resolveAndCreate HTTP method in Angular2

During the time of RC4, I was able to create my own custom http instance using a function like this: export function createHTTP(url:string, headers?:Headers){ let injector = ReflectiveInjector.resolveAndCreate([ myHttp, {provide:'defaultUrl ...

How to efficiently update a child component in React using UseState and establish a connection back to the parent component

I am currently working on developing a prototype for a master/detail scenario in React and Material-UI. The task involves creating a basic list of objects with the ability to edit and save an item using a dialog. While I have successfully updated the visit ...

Injecting Dependencies with Angular 2 and the Ability to Include Optional Parameters

One issue I'm facing is that I have multiple components in my Angular 2 application that require the same dependency. This specific dependency needs a string for the constructor. How can I instruct angular2 to use a specific instance of this type for ...

Utilizing Typescript: Ensuring an array includes only specified values from an enum through strict enforcement

In my Angular application, I have an HTTP service that returns the allowed accesses for a specific user. The response structure is as shown below:- { "accessId": 4209318492034, "folderPath": "data/sample_folder/", ...

Distinguish between a function and a constructor during execution

As I work with TypeScript, I am creating a function that accepts an error factory as an argument. This factory can be either a class name or a function. The function looks something like this: // Alias from class-transformer package type ClassConstructor& ...

Using scrollIntoView() in combination with Angular Material's Mat-Menu-Item does not produce the desired result

I am facing an issue with angular material and scrollIntoView({ behavior: 'smooth', block: 'start' }). My goal is to click on a mat-menu-item, which is inside an item in a mat-table, and scroll to a specific HTML tag This is my target ...

Attempt the HTTP request again only for specific status codes

When developing my Angular application, I encountered a situation where I needed to make an HTTP call to a backend server. To enhance its reliability, I decided to incorporate an interceptor to implement the retry pattern. In the past, I utilized RxJS&apo ...

Learn the steps to establish a one-to-many relational record with the help of Node.js and Sequelize-Typescript

Currently, I am working on Nodejs with sequelize-typescript to develop a CRUD system for a one-to-many relationship. Unfortunately, I have encountered an issue with my code that I cannot seem to pinpoint. While I am able to retrieve records successfully us ...

What is the method for adding attributes to a class dynamically in TypeScript so that they can be accessed by instances?

I attempted to create a universal factory function that generates custom enum objects, but the instances were not able to retrieve the correct properties. Take a look at the preview of the code online: https://stackblitz.com/edit/typescript-rkl1zr Workin ...

A more efficient way to specify children types in Typescript React is by directly specifying the type in the function instead

What is the reason behind this: interface UserSidebarProps { children? : React.ReactNode } function UserSidebar({children}: UserSidebarProps) { return ( <div> {children} </div> ) } Why doesn't this work? function User ...

"Resulting in 'undefined' due to an asynchronous function call

Encountering an issue with async method implementation. In my authServices, there is a loginWithCredential function which is asynchronous: async loginWithCredential(username, password){ var data = {username: username, password: password}; api.pos ...

Error TS2322: The function expecting a type of 'FormEventHandler<HTMLFormElement>' cannot be assigned the type '(data: TicketFullDTO) => Promise<void>'

I am currently working on creating an edit form to modify data from a database based on its ID. Here is my approach: import React, {FormEvent, useEffect, useState} from "react"; import TextField from "@material-ui/core/TextField" ...

Is it possible to capture user input using a rich text editor such as Quill and save the data as a .json file by sending a POST request?

My website features a sophisticated text editor known as ngx-quill, where users can input their content. I am currently working on a project that requires me to generate a JSON file containing user input and then submit this JSON file. I am seeking guidan ...

What is the proper way to specifically define a new property on the `global` object in TypeScript?

I want to define a type signature for the variable below: (global as any).State = { variables: {}, }; How can I declare the type of State? If I try (global as any).State: Something = ..., the compiler displays an error message saying ; expected. It se ...

Is it time to launch your React TypeScript application on AWS S3?

I need help transitioning my deployment from AWS S3 using JavaScript to TypeScript. What specific code should I incorporate in TypeScript to facilitate this transition? 1) I have downloaded files with a .ts extension. https://i.sstatic.net/He49G.jpg 2) H ...

Choose from the Angular enum options

I am working with an enum called LogLevel that looks like this: export enum LogLevel { DEBUG = 'DEBUG', INFO = 'INFO', WARNING = 'WARNING', ERROR = 'ERROR' } My goal is to create a dropdown select el ...