mirror of
https://github.com/ruanyf/es6tutorial.git
synced 2025-05-24 10:22:23 +00:00
docs(object): add Object.fromEntries
This commit is contained in:
parent
7a151448f7
commit
b48ce465ba
@ -733,9 +733,9 @@ Object.values(42) // []
|
||||
Object.values(true) // []
|
||||
```
|
||||
|
||||
### Object.entries
|
||||
### Object.entries()
|
||||
|
||||
`Object.entries`方法返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历(enumerable)属性的键值对数组。
|
||||
`Object.entries()`方法返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历(enumerable)属性的键值对数组。
|
||||
|
||||
```javascript
|
||||
const obj = { foo: 'bar', baz: 42 };
|
||||
@ -795,3 +795,40 @@ function entries(obj) {
|
||||
}
|
||||
```
|
||||
|
||||
## Object.fromEntries()
|
||||
|
||||
`Object.fromEntries()`方法是`Object.entries()`的逆操作,用于将一个键值对数组转为对象。
|
||||
|
||||
```javascript
|
||||
Object.fromEntries([
|
||||
['foo', 'bar'],
|
||||
['baz', 42]
|
||||
])
|
||||
// { foo: "bar", baz: 42 }
|
||||
```
|
||||
|
||||
该方法的主要目的,是将键值对的数据结构还原为对象,因此特别适合将 Map 结构转为对象。
|
||||
|
||||
```javascript
|
||||
// 例一
|
||||
const entries = new Map([
|
||||
['foo', 'bar'],
|
||||
['baz', 42]
|
||||
]);
|
||||
|
||||
Object.fromEntries(entries)
|
||||
// { foo: "bar", baz: 42 }
|
||||
|
||||
// 例二
|
||||
const map = new Map().set('foo', true).set('bar', false);
|
||||
Object.fromEntries(map)
|
||||
// { foo: true, bar: false }
|
||||
```
|
||||
|
||||
该方法的一个用处是配合`URLSearchParams`对象,将查询字符串转为对象。
|
||||
|
||||
```javascript
|
||||
Object.fromEntries(new URLSearchParams('foo=bar&baz=qux'))
|
||||
// { foo: "bar", baz: "qux" }
|
||||
```
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user