0

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

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

3 Answers 3

4

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.