How do I convert the string below to key-value pairs
TotalCount:100,PageSize:10,CurrentPage:1,TotalPages:10,HasNext:true,HasPrevious:false
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);
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],
};
}, {});