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

A function in Typescript that dynamically determines its return type based on a specified generic parameter

Currently, I am attempting to create a function where the return type is determined by a generic argument. Let me share a code snippet to illustrate: type ABCDE = 'a' | 'b'; function newFunc<U extends ABCDE>(input: U): U extends ...

How to determine the presence of 'document' in Typecsript and NextJS

Incorporating NextJS means some server-side code rendering, which I can manage. However, I'm facing a challenge when trying to check for set cookies. I attempted: !!document && !!document.cookie as well as document !== undefined && ...

Event-Propagation in Angular 5 with mat-expansion-panel within another component

In my project, I am facing a challenge where I need to create multiple mat-expansion-panels within one mat-expansion-panel. Everything works fine except for the issue that when I try to open a child-panel, it triggers the close-event of the parent-panel. ...

"Benefit from precise TypeScript error messages for maintaining a streamlined and organized architecture in your

As I dip my toes into the world of functional programming with typescript for a new project, I am encountering some challenges. In the provided code snippet, which follows a clean architecture model, TypeScript errors are popping up, but pinpointing their ...

The "ng2-CKEditor" package is experiencing compatibility issues with TypeScript in Angular 2

Currently, I am in the process of setting up CKEditor in my angular2 application. My backend platform is node.js and for this purpose, I am utilizing the ng2-CKEditor npm module. Below, you can find snippets from respective files. index.html:: <html& ...

Angular 4 Operator for adding elements to the front of an array and returning the updated array

I am searching for a solution in TypeScript that adds an element to the beginning of an array and returns the updated array. I am working with Angular and Redux, trying to write a reducer function that requires this specific functionality. Using unshift ...

What is the best way to loop through the keys of a generic object in TypeScript?

When I come across a large object of unknown size, my usual approach is to iterate over it. In the past, I've used generators and custom Symbol.iterator functions to make these objects iterable with a for..of loop. However, in the ever-evolving world ...

The issue with Multiselect arises when the array is being set up initially

Using primeng Multiselect, I have implemented a logic to push data based on search value from the backend. To avoid the error of pushing undefined elements, initialization is required before pushing. However, when I initialize the dropdown's array var ...

Tips for managing open and closed components within a React accordion and ensuring only the clicked component is opened

Unique Accordion component: const CustomAccordion = (props: AccordionProps) => { const { label, levels, activeId, id } = props const [isExpand, setIsExpand] = useState(false) const onPress = useEvent(() => { setIsExpand( ...

Troubleshooting Missing Exports from Local Modules in React Vite (Transitioning from Create React App)

I have encountered an issue while trying to import exported members from local nodejs packages in my project. Everything was working fine with the standard CRA webpack setup, but after switching to Vite, I started getting the following error: Unca ...

When utilizing the Angular 2 Stack, the Typescript Reflect.getMetadata('design:type'...) method may return an Object instead of a Date

When running the code sample below, it outputs "[Function: Date]", which is as expected. import 'reflect-metadata' function logType(target : any, key : string) { var t = Reflect.getMetadata("design:type", target, key); console.log(`${k ...

What are the distinctions between using getStaticPaths + getStaticProps and useRouter in NextJS?

I'm currently diving into the world of NextJS and finding myself puzzled by the distinctions between getStaticProps & getStaticPaths compared to utilizing useRouter().query. At this point, it appears to me that both methods serve a similar purpos ...

Having trouble retrieving information from combineLatest in Angular?

I'm having some trouble with fetching files to include in the post logs. It seems that the data is not being passed down the chain correctly when I attempt to use the pipe function after combining the latest data. This code snippet is part of a data r ...

A Promise-based value returned by a Typescript decorator with universal methods

I am currently working on creating a method decorator that can be applied to both prototype and instance methods. Referenced from: Typescript decorators not working with arrow functions In the code provided below, the instanceMethod() is returning a Prom ...

TypeScript: empty JSON response

I am encountering an issue with the JSON data being blank in the code below. The class is defined as follows: export class Account { public amount: string; public name: string; constructor(amount: string, name: string) { this.amount = amount; t ...

Issue with NgModule in Angular application build

I'm facing an issue with my Angular application where the compiler is throwing errors during the build process. Here's a snippet of the error messages I'm encountering: ERROR in src/app/list-items/list-items.component.ts:9:14 - error NG6002 ...

Ways to determine if a date matches today's date within a component template

I am currently displaying a list of news articles on the webpage and I want to show the word "Today" if the news article's date is equal to today's date. Otherwise, I want to display the full date on the page. Is there a way to compare the news.D ...

Using @Input to pass data from a parent component to a

Looking to modularize the form code into a separate component for reusability? Consider using @Input and referencing it in the HTML to pass values to the post method. Here's how you can achieve this: Previously, everything worked smoothly when all th ...

A guide on transforming a string into an array of objects using Node.js

Hey everyone, I have a single string that I need to convert into an array of objects in Node.js. let result = ""[{'path': '/home/media/fileyear.jpg', 'vectors': [0.1234, 0.457, 0.234]}, {'path': '/home/med ...

What could be causing the lack of updates in my SolidJS component when the data changes?

One of my components in SolidJS is an Artist page component. Here is a snippet of the code: export function Artist() { const params = useParams<{ id: string }>(); const [data, setData] = createSignal(null); createEffect(() => { fetchArti ...