Home > Net >  converting a string to key value pairs in Typescript
converting a string to key value pairs in Typescript

Time:07-12

How do I convert the string below to key-value pairs

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

CodePudding user response:

With the help of String.split() method, you can split and then use reduce method and add the key value pair into object.

const string = "TotalCount:100,PageSize:10,CurrentPage:1,TotalPages:10,HasNext:true,HasPrevious:false";

const result = string.split(',').reduce((acc, item) => {

  const keyValue = item.split(':');
  
  return {...acc, [keyValue[0]]: keyValue[1]}

}, {});

console.log(result);

CodePudding user response:

You can do it like that:

const myValues = "TotalCount:100,PageSize:10,CurrentPage:1,TotalPages:10,HasNext:true,HasPrevious:false"

const myObj = {};

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

console.log(myObj);

CodePudding user response:

using reduce and maintainance the type

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],
    };
  }, {});
  • Related