1. Object.fromEntries()
Map转化为Object
const map = new Map([ ['foo', 'bar'], ['baz', 42] ]);
// {"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()
的反转函数, 借用 array manipulation methods 可以转换对象,如下:
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 }
网友评论