ECMAScript question detail
Object fromEntries
In JavaScript, it is very common to transforming data from one format. ES2017 introduced Object.entries() method to objects into arrays.
Object to Array:
const obj = {'a': '1', 'b': '2', 'c': '3' };
const arr = Object.entries(obj);
console.log(arr); // [ ['a', '1'], ['b', '2'], ['c', '3'] ]
But if you want to get the object back from an array then you need iterate and convert it as below,
const arr = [ ['a', '1'], ['b', '2'], ['c', '3'] ];
let obj = {}
for (let [key, val] of arr) {
obj[key] = val;
}
console.log(obj);
We need a straightforward way to avoid this iteration. In ES2019, Object.fromEntries() method is introduced which performs the reverse of Object.entries() behavior. The above loop can be avoided easily as below,
Iterable( e.g Array or Map) to Object
const arr = [ ['a', '1'], ['b', '2'], ['c', '3'] ];
const obj = Object.fromEntries(arr);
console.log(obj); // { a: "1", b: "2", c: "3" }
One of the common case of this method usage is working with query params of an URL,
const paramsString = 'param1=foo¶m2=baz';
const searchParams = new URLSearchParams(paramsString);
Object.fromEntries(searchParams); // => {param1: "foo", param2: "baz"}