1
0
mirror of https://github.com/ruanyf/es6tutorial.git synced 2025-05-24 18:32:22 +00:00

docs(object): add Object.fromEntries

This commit is contained in:
ruanyf 2018-11-10 13:14:52 +08:00
parent 7a151448f7
commit b48ce465ba

View File

@ -733,9 +733,9 @@ Object.values(42) // []
Object.values(true) // [] Object.values(true) // []
``` ```
### Object.entries ### Object.entries()
`Object.entries`方法返回一个数组成员是参数对象自身的不含继承的所有可遍历enumerable属性的键值对数组。 `Object.entries()`方法返回一个数组成员是参数对象自身的不含继承的所有可遍历enumerable属性的键值对数组。
```javascript ```javascript
const obj = { foo: 'bar', baz: 42 }; 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" }
```