Transforming a string into key-value pairs using Typescript

Is there a way to transform the given string into key-value pairs?

TotalCount:100,PageSize:10,CurrentPage:1,TotalPages:10,HasNext:true,HasPrevious:false

Answer №1

Learn how to effectively utilize the String.split() method in JavaScript for splitting strings and then leveraging the reduce method to add key-value pairs into an object.

const data = "Name:John,D.O.B:01-01-1990,Location:New York,Hobbies:Tennis,Swimming";

const resultObject = data.split(',').reduce((accumulator, item) => {

  const [key, value] = item.split(':');
  
  return {...accumulator, [key]: value};

}, {});

console.log(resultObject);

Answer №2

Here is a way to achieve the desired result:

let dataString = "Title:Ocean,Depth:100ft,Temperature:75°F,MarineLife:Various"

const dataObject = {};

dataString.split(",").forEach(item => {
  dataObject[item.split(":")[0]] = item.split(":")[1]
});

console.log(dataObject);

Answer №3

Implementing reduce function for type preservation

result = this.string.split(',').reduce((a: any, b: string) => {
    const pairValue = b.split(':');
    return {
      ...a,
      [pairValue[0]]:
        pairValue[1] == 'true'
          ? true
          : pairValue[1] == 'false'
          ? false
          : '' + (+pairValue[1]) == pairValue[1]
          ? +pairValue[1]
          : pairValue[1],
    };
  }, {});

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

What sets apart HttpClient.post() from creating a new HttpRequest('POST') in Angular?

I've recently started learning angular, and I've noticed that there are two different ways to make a POST request: constructor(private httpClient: HttpClient) { httpClient.post(url, data, options); } constructor(private httpClient: HttpClie ...

Differences between Angular's form builder and form control and form groupIn the

What are the benefits of using form control and form group instead of form builder? Upon visiting this link, I discovered: The FormBuilder simplifies creating instances of a FormControl, FormGroup, or FormArray by providing shorthand notation. It helps ...

What is the process for loading a script file from within a component's HTML?

My goal was to include a specific script file in the component html, but I noticed that when I added the script reference within the html itself, the inner script file was not rendered along with the component on the page. Component import { Component } ...

Angular - Set value on formArrayName

I'm currently working on a form that contains an array of strings. Every time I try to add a new element to the list, I encounter an issue when using setValue to set values in the array. The following error is displayed: <button (click)="addNewCom ...

Vue.js is unable to recognize this type when used with TypeScript

In my code snippet, I am trying to set a new value for this.msg but it results in an error saying Type '"asdasd"' is not assignable to type 'Function'. This issue persists both in Visual Studio and during webpack build. It seems like Ty ...

What is the best way to indicate a particular element within a subdocument array has been altered in mongoose?

I have a specific structure in my Mongoose schema, shown as follows: let ChildSchema = new Schema({ name:String }); ChildSchema.pre('save', function(next){ if(this.isNew) /*this part works correctly upon creation*/; if(this.isModifi ...

Should an HTML canvas in Angular be classified as a Component or a Service?

I have a basic drawing application that uses an MVC framework in TypeScript, and I am looking to migrate it to Angular. The current setup includes a Model for data handling, a View for rendering shapes on the canvas, and a Controller to manage interactio ...

TypeScript: implementing function overloading in an interface by extending another interface

I'm currently developing a Capacitor plugin and I'm in the process of defining possible event listeners for it. Previously, all the possible event listeners were included in one large interface within the same file: export interface Plugin { ...

Best practices for applying the Repository pattern within a NestJS application

After reviewing the NestJS documentation and examining their sample source codes, it appears challenging to implement a Repository pattern between the service layer and the database layer (e.g. MongoDB). In NestJS, database operations are executed directl ...

Ways to transfer data from TypeScript to CSS within Angular 6

Trying to work with ngClass or ngStyle, but I'm struggling with passing the value. Here's my current code: strip.component.ts import { ... } from '@angular/core'; @Component({ selector: 'app-strip', templateUrl: &apo ...

Angular 2 error: "HttpService Provider Not Found"

In my Angular 2 / Ionic 2 project, I have the following "constellation" of components and services: Component1 -> Service1 -> Service3 Component2 -> Service2 -> Service3 (where -> denotes a relationship like "using" or "calling") Whenever I ...

Place the Div in a consistent position on images of varying widths

I have a dilemma with my class that is supposed to display images. The issue arises when I try to place a div within an image inside this class. Everything works smoothly when the image takes up the entire width of the class, but as soon as the image widt ...

Tips for effectively managing index positions within a dual ngFor loop in Angular

I'm working on a feedback form that includes multiple questions with the same set of multiple choice answers. Here's how I've set it up: options: string[] = ['Excellent', 'Fair', 'Good', 'Poor']; q ...

Firebase authentication link for email sign-in in Angularfire is invalid

Currently, I am utilizing the signInWithEmailLink wrapper from AngularFire for Firebase authentication. Despite providing a valid email address and return URL as arguments, an error is being thrown stating "Invalid email link!" without even initiating any ...

What steps are required to generate dist/app.js from a script file in my TypeScript project?

I am currently working on a project using node, express, and TypeScript. When I run npm run build, everything builds without any issues. However, when I attempt to run npm run start, I encounter the following error: @ruler-mobility/[email protected] /User ...

Your global Angular CLI version (6.1.2) surpasses that of your local version (1.5.0). Which version of Angular CLI should be used locally?

I am experiencing an error where my global Angular CLI version (6.1.2) is higher than my local version (1.5.0). Can someone provide assistance with this issue? Below are the details of my local versions: Angular CLI: 1.5.0 Node: 8.11.3 OS: win32 ia32 Ang ...

Do we really need to use redux reducer cases?

Is it really necessary to have reducers in every case, or can actions and effects (ngrx) handle everything instead? For instance, I only have a load and load-success action in my code. I use the 'load' action just for displaying a loading spinne ...

The link button appears unselected without a border displayed

I am facing an issue with a link button in my code. Here is the snippet: <div class="col-2"> <a type="button" routerLink="auto-generate-schedules/generate" class="btn btn-primary mb-2">Generate Sche ...

Steps to activate or deactivate a button in Angular 2 depending on required and non-required fields

I am looking to have the Save button activated when the Placeholder value is set to 'Optional'. If the value is set to 'Mandatory', then the Save button should be deactivated and only become active if I input a value for that field. He ...

TypeScript mandates the inclusion of either one parameter or the other, without the possibility of having neither

Consider the following type: export interface Opts { paths?: string | Array<string>, path?: string | Array<string> } The requirement is that the user must provide either 'paths' or 'path', but it is not mandatory to pa ...