ES10(2019)Object.fromEntries()

Posted 优小U

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ES10(2019)Object.fromEntries()相关的知识,希望对你有一定的参考价值。

Object.fromEntries() 方法把键值对列表转换为一个对象

const entries = new Map([
  ['foo', 'bar'],
  ['baz', 42]
]);
const obj = Object.fromEntries(entries);
console.log(obj); //  {"foo":"bar","baz":42}

类似 ArrayMap 或者其它实现了可迭代协议的可迭代对象都可以使用。

// Map 转换为 Object
const map = new Map([ ['foo', 'bar'], ['baz', 42] ]);
const obj = Object.fromEntries(map);
console.log(obj); // { foo: "bar", baz: 42 }

// Array 转换为 Object
const arr = [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ];
const obj = Object.fromEntries(arr);
console.log(obj); // { 0: "a", 1: "b", 2: "c" }

Object.fromEntries 是与 Object.entries() 相反的方法:

const object1 = { a: 1, b: 2, c: 3 };
const object2 = Object.fromEntries(
  Object.entries(object1).map(([ key, val ]) => [ key, val * 2 ])
);
console.log(object2);
// { a: 2, b: 4, c: 6 }

场景:过滤

const course = {
    math: 80,
    english: 85,
    chinese: 90
}
const res = Object.entries(course).filter(([key, val]) => val > 80)
console.log(res)  //  [["english",85],["chinese",90]]
console.log(Object.fromEntries(res)) //  {"english":85,"chinese":90}

以上是关于ES10(2019)Object.fromEntries()的主要内容,如果未能解决你的问题,请参考以下文章

ES10(2019)可选的Catch Binding

ES10(2019)——JSONArrayObjectFunctiontry.catchBigInt 能力升级

ES10(2019)——JSONArrayObjectFunctiontry.catchBigInt 能力升级

ES10(2019)新特性

ES10(2019)Object.fromEntries()

ES10(2019)Symbol 扩展 Symbol.prototype.description