键值对列表转换为一个对象,与 Object.entries() 相对的(互逆)

    1. const entries = new Map([
    2. ["key1", "value1"],
    3. ["key2", "value2"],
    4. ]);
    5. const obj = Object.fromEntries(entries);
    6. console.log(obj); // { key1: 'value1', key2: 'value2' }

    Map 转化为 Object

    1. const map = new Map([
    2. ["foo", "bar"],
    3. ["baz", 42],
    4. ]);
    5. // const map = new Map();
    6. // map.set('key1','value1')
    7. // map.set('key2','value2')
    8. const obj = Object.fromEntries(map);
    9. console.log(obj); // { key1: 'value1', key2: 'value2' }

    Array 转化为 Object

    1. const arr = [
    2. ["0", "a"],
    3. ["1", "b"],
    4. ["2", "c"],
    5. ];
    6. const obj = Object.fromEntries(arr);
    7. console.log(obj); // { 0: 'a', 1: 'b', 2: 'c' }

    对象转换

    1. const course = {
    2. abc: 1,
    3. def: 2,
    4. ghksks: 3,
    5. };
    6. const res = Object.fromEntries(
    7. Object.entries(course).filter(([key, val]) => key.length === 3)
    8. );
    9. console.log(res);