-1

I am using ajax to send FormData and receiving the output in the following format

Result=A&Status=Approved&Error=&ErrorCode=00000

I want to convert the same into a JS object (key value pair) e.g.

{Result: "A", Status: "Approved", Error: "", ErrorCode: "00000"}

I can do that using string split and other string functions or regex but since the output format is consistent i was wondering if this is a known data type and if yes is there a way to convert it using native functions?

Arun
  • 59
  • 1
  • 8

2 Answers2

1

You can use Object.fromEntries in conjunction with the URLSearchParams constructor.

const obj = Object.fromEntries(new URLSearchParams(
    'Result=A&Status=Approved&Error=&ErrorCode=00000'));
console.log(obj);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • Since the data was not retrieved from the url, I never looked at it like GET parameters. URLSearchParams works as intended. – Arun Oct 03 '22 at 15:30
-1

Take a look at new URLSearchParams(), it should be a way better solution than string manipulation.

red-X
  • 5,108
  • 1
  • 25
  • 38