1

I have some string like this

 const resultComing ='access_token=test&token_type=bearer&state=state&expires_in=43199&scope=test';

I need to passed to object that will look like this

const result: any = {
  access_token: test,
  token_type: bearer,
  state: state,
  expires_in: 43199,
  scope: test
};

I have tried like this

const result: any = resultComing.split('&').reduce(function (result: any, item: string) {
  const parts = item.split('=');
  result[parts[0]] = parts[1];
}, {});

But i got error, TypeError: Cannot set property 'token_type' of undefined

2
  • Does this work for you? It's a little more readable and does exactly what you want. Commented Apr 15, 2020 at 12:43
  • This is good solution, can you write an answer thanks Commented Apr 15, 2020 at 12:51

3 Answers 3

1

Your function doesnt work because as Niet said, you dont return anything from the Array.reduce() function and so the next time it iterates over it, result will be undefined.

To fix it, simply return the result at the end:

const result: any = resultComing.split('&').reduce(function (result: any, item: string) {
    const parts = item.split('=');
    result[parts[0]] = parts[1];
    return result;
}, {});

If you don't want the arrow function, you can also go over your pairs with a simple loop:

let obj: any = {};
let pairs = resultComing.split('&');

for (let pair of pairs) {
    let parts = pair.split('=');
    obj[parts[0]] = parts[1];
}

Playground Link

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

Comments

0

The result array you are calling within the following line is never intitiated and therefore.

result[parts[0]] = parts[1];

try the following:

const result: any = {};
resultComing.split('&').reduce(function (result: any, item: string) {
  const parts = item.split('=');
  result[parts[0]] = parts[1];
}, {});

2 Comments

result is the "current" parameter in the reduce() call.
non-arrow functions are forbidden (only-arrow-functions)
0

.reduce()'s callback expected something to be returned.

const [k,v] = item.split("=");
result[k] = v;
return result;

This is why the error you get is only on the second key. For the first key, it passes your "initial" value of {} into the function and works just fine, but since the function doesn't return anything then the second call has undefined and you can't set properties on that.

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.