Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over JavaScript URL Object's Properties

Tags:

javascript

w3c

I'm trying to map an instance of JavaScript's URL class to a plain object and can't understand why it's not working.

I'm guessing this is because the properties are not enumerable, but it's not clear to me why this would be the case.

let input = 'https://www.google.com/index.html?bar=baz#foo'

let url = new URL(input)

console.log(url.origin)
console.log(url.protocol)
console.log(url.host)
console.log(url.pathname)
console.log(url.hash)
console.log(url.search)

let urlMap = Object.entries(url).reduce((map, [key, value]) => {
  map[key] = value
  return map
}, {})


console.log(urlMap)  // returns {}

Is this something I can do? My goal was to compose the url properties like this:

return { ...url, pathname: alteredPathname }
like image 493
Matt Morgan Avatar asked Dec 13 '25 04:12

Matt Morgan


1 Answers

If you check the _proto of url instance you will see, those fields are getters and setters. Therefor Object.entries / keys won't work here

enter image description here

Howeve loop below should work

const input = 'https://www.google.com/index.html?bar=baz#foo'

const url = new URL(input)
const map = {};
for (let key in url) {
  map[key] = url[key]
}

console.log(map);

Here is the output Here is the output

like image 130
Arif Avatar answered Dec 15 '25 17:12

Arif



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!