Strip Line Breaks and Spaces from JSON Object Keys using TypeScript

After converting a Json object from an Excel sheet, I noticed that some keys have line breaks and spaces. I need a function to remove all line breaks and spaces from the json object's keys. Here is the structure of the json:

 {"SOH":[{"MN":"asdf","Part\r\nNumber":"1234"},{"MN":"asdf2","Part\r\nNumber":"12343"}]} 

The expected outcome should look like this:

 {"SOH":[{"MN":"asdf","PartNumber":"1234"},{"MN":"asdf2","PartNumber":"12343"}]} 

Thank you for your support!

Answer №1

To achieve this, you can utilize the combination of Object.entries(), map(), and replace() in order to reconstruct objects with updated values.

const obj = {
  "SOH": [
    { "MN": "asdf", "Part\r\nNumber": "1234" },
    { "MN": "asdf2", "Part\r\nNumber": "12343" }
  ]
};

const result = {
   "SOH": obj.SOH.map(o => {
      return Object.fromEntries(Object.entries(o).map(([k, v]) => [k.replace(/(\n|\s)/g, ""), v]));
   })
};
console.log(result);

If you are looking for a more dynamic approach...

const obj = {
   "SOH": [
      { "MN": "asdf", "Part\r\nNumber": "1234" },
      { "MN": "asdf2", "Part\r\nNumber": "12343" }
   ],
   "MOH": [
      { "MN": "asdf", "Part\r\nNumber": "1234" },
      { "MN": "asdf2", "Part\r\nNumber": "12343" }
   ],
   "KOH": [
      { "MN": "asdf", "Part\r\nNumber": "1234" },
      { "MN": "asdf2", "Part\r\nNumber": "12343" }
   ]
};

const result = Object.fromEntries(Object.entries(obj).map(([k, v]) => {
   return [k, v.map(x => Object.fromEntries(Object.entries(x).map(([kk, vv]) => [kk.replace(/(\n|\s)/g, ""), vv])))]
}));

console.log(result);

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

The Reason Behind Angular Error when Using CSS Custom Tags

I have the following SCSS code: main{ width: 100%; height: 840px; /*background: red;*/ margin: 10px auto; position: relative; padding: 5px 0; } section{ width: 98%; height: 600px; margin: auto; display: flex; ...

The onChange function in React is not behaving as I anticipated

Consider the following data structure for tables: an array of objects containing nested objects: [ { "1": { "1": "Item s ", "2": "Manufacturer ", "3" ...

Angular material tables are displaying borders that do not extend the full length

I am currently working on designing a visually appealing table. Due to the upcoming content in the matrix section, I am unable to make the table smaller for mobile devices. Therefore, I have added overflow:auto to enable a scroll-bar. The issue I am facin ...

The link function fails to execute

I have created a custom Directive. The issue I am facing is that the html template is not being rendered. Upon debugging, I noticed that the link function is never called because the instance function is also never called. To troubleshoot, I added "debu ...

The sequence of initializing test hooks in inconsistent playwright tests

My testing framework setup looks something like this: test.describe("...", () => { let p: Page; test.beforeEach(async({browser}) => { p = await (await browser.newContext()).newPage(); } test(...); test(...); test.aft ...

Utilize the text box feature for manipulating the data field in Angular4

Within my grid view, there exists a column labeled remark. This specific field contains various values, one of which is absence. My objective is to modify the remark value exclusively when it is equal to absence, followed by clicking the corresponding icon ...

Ways to fix: Unable to locate package 'xlsx'

I'm encountering an issue with the xlsx package in my UI5 project (using TypeScript) as it is unable to find the module. Can someone please help me with resolving this problem? Here is how I am importing it in my main.controller.ts file: import { XLS ...

Navigating with the InAppBrowser in Ionic Angular after a POST request

Currently, I am in the process of redirecting my app to 3DS for a payment method. According to the documentation, the steps involved are: Obtain the action.url and the action.method from the /payments response. Redirect the shopper to the specified URL us ...

The letter 'T' has the flexibility to be assigned with any type, even those that are completely unrelated

Currently, I am developing an endpoint within Next.js. My goal is to strictly enforce the JSON structure returned by API endpoints. It would be very beneficial if I could automatically infer the return type of an endpoint and utilize that information in my ...

Unraveling Angular2 Dependency Injection: Decoding the mysterious syntax seen preceding certain injected package names (e.g. 'providers = [...SomeProvider]')

As I delve into learning Angular2, I have stumbled upon a new syntax for injecting providers. providers : [SomeProvider], Interestingly, some packages are now using a "..." before the provider name like this: providers : [...SomeProvider], This got me ...

Filtering through an array object with PrimeNG

Is it feasible to utilize an array of objects for filtering data in a table? I'm currently using Angular 6 and PrimeNG 7. This is how my p-table appears: <p-table #table class="ui-table ui-table-responsive" [value]="arrays" [columns]="cols" > ...

The type 'Promise<UserCredential>' cannot be assigned to

import React, {createContext, useContext, useEffect, useState, ReactNode} from "react"; import { auth } from '../utils/init-firebase'; import { createUserWithEmailAndPassword } from "firebase/auth" type ButtonProps = { ch ...

Instructions for activating the "Navigate to Declaration" feature in TypeScript for JSON files using i18next

Currently, I am actively engaged in a project that involves the use of i18next with react and typescript. In this project, translation keys are defined within .json files. However, a notable drawback of transitioning to json for the translation files is l ...

TS: Utilizing a generic parameter in an overloaded function call

This piece of code encapsulates the essence of what I'm trying to achieve more effectively than words: function A(a: string): string; function A(a: number): number; function A(a: any) { return a; } function B<T extends number | string>(arg: T): ...

There is a compatibility issue between the module and the engine "node" in this instance

Upon running the command npx create-react-app my-awesome-react-app --template typescript, I encountered the following yarn error: Error [email protected]: The engine "node" is incompatible with this module. Expected version "^6 || ^7 || ^8 || ^9 || ^10 || ...

Angular: The type AbstractControl<any> cannot be assigned to type FormControl

I am working with a child component that includes an input tag <input [formControl]="control"> component.ts file @Input() control: FormControl; In the parent component, I am using it as follows: <app-input [control]="f['email ...

Guide on transforming absolute imports into relative imports using Rollup.js?

Currently in the process of reorganizing my code and rewriting some TypeScript modules that are anticipated to be utilized by multiple microservices as packages. Encountering an issue with absolute imports enabled by baseUrl in relation to this package co ...

Guide on expanding the capabilities of IterableIterator in TypeScript

I am currently working on extending the functionality of Iterable by adding a where method, similar to C#'s Enumerable.where(). While it is straightforward to extend the Array prototype, I am encountering difficulties in figuring out how to extend an ...

Sorting through items within a container object

I am currently working with an object named 'docs' that contains multiple objects within it. I am attempting to determine the count of entries that have specific values for both 'exopp_rooms_id_c' and 'is_active'. While this m ...

Debugging is not possible for applications running on an Android device with Ionic 2

Instructions to replicate the issue: 1. Begin by creating a new project from the following repository: https://github.com/driftyco/ionic-starter-super 2. Execute the command `ionic run android` 3. Utilize chrome://inspect for debugging purposes The ...