简体   繁体   English

遍历JavaScript URL对象的属性

[英]Iterate over JavaScript URL Object's Properties

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. 我正在尝试将JavaScript的URL类的实例映射到一个普通对象,并且无法理解为什么它不起作用。

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: 我的目标是像这样编写url属性:

return { ...url, pathname: alteredPathname }

If you check the _proto of url instance you will see, those fields are getters and setters. 如果您检查url实例的_proto,您将看到,这些字段是getter和setter。 Therefor Object.entries / keys won't work here 因此Object.entries /键在这里不起作用

在此处输入图片说明

Howeve loop below should work 下面的Howeve循环应该工作

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 这是输出 这是输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM