I'm trying to get a js object from an URL key:value pairs. For that I'm using "Object.fromEntries()" but when I got the result, it returns an object with all the keys quoted, so when I try to access its value I got an error.
Does somebody knows how to solve that, pls?
This is the code:
const params = window.location.search;
const obj = Object.fromEntries(new URLSearchParams(params))
console.log(obj);
...and this is what it returns back:
Object { "user-name": "phill", "user-lastname": "smith" }
How can I remove quotes from: user-name and user-lastname keys.?
You can't remove the quotes, because keys with special characters require quotes. However, you can access them using brackets notation obj['user-name'].
The other option is to get the param from the URLSearchParams instance using URLSearchParams.get():
const params = 'user-name=phill&user-lastname=smith';
const searchParams = new URLSearchParams(params);
const obj = Object.fromEntries(searchParams)
console.log(searchParams.get('user-name'));
console.log(obj['user-name']);