键值对列表转换为一个对象,与 Object.entries() 相对的(互逆)
javascript
const entries = new Map([
['key1', 'value1'],
['key2', 'value2'],
])
const obj = Object.fromEntries(entries)
console.log(obj) // { key1: 'value1', key2: 'value2' }
Map 转化为 Object
javascript
const map = new Map([
['foo', 'bar'],
['baz', 42],
])
// const map = new Map();
// map.set('key1','value1')
// map.set('key2','value2')
const obj = Object.fromEntries(map)
console.log(obj) // { key1: 'value1', key2: 'value2' }
Array 转化为 Object
javascript
const arr = [
['0', 'a'],
['1', 'b'],
['2', 'c'],
]
const obj = Object.fromEntries(arr)
console.log(obj) // { 0: 'a', 1: 'b', 2: 'c' }
对象转换
javascript
const course = {
abc: 1,
def: 2,
ghksks: 3,
}
const res = Object.fromEntries(
Object.entries(course).filter(([key, val]) => key.length === 3)
)
console.log(res)