const foo = bar.reduce((hash, item) => { hash[item.id] = item; return hash; }, {});
new Map([[k1,v1], [k2, v2]]) can do that. Or Object.fromEntries with the same argument.
Re:Deno Joins TC39
by tarjei_huse on Monday December 13, 2021 @09:42AM
(#29539980)
Thanks!
You still need to create the middle datastructure ( [[k1,v1], [k2, v2]] ) but it is an improvement :)
Ah yes, true, you always need to map the things ID to the thing itself, so that middle data structure is actually quite annoying :)
let foo = Object.fromEntries(bar.map((v) => [v.id, v]));It is not necessary to create any extraneous data structures to do OP's one-liner. This creates n+1 new arrays that must be garbage-collected.
Object.fromEntries takes iterable, so if you have a map from a handy iterator library you could get rid of the parent array returned from `bar.map`.
import { map } from "my-iter-lib";
Object.fromEntries(map((v) => [v.id, v], bar));
Or with the proposed iterator-helpers: Object.fromEntries(
Iterator.from(bar).map((v) => [v.id, v]),
)
However the inner arrays are harder to get rid of... In fact even OP’s oneliner defines the inner arrays. I would hope there were some engine optimizations though which could minimize their footprint.
let bar = [{id: zz, }, {id: y},...]
let foo = {}
bar.forEach(v => foo[v.id] = v)
I'd love to have something like:
let foo = bar.toMap(v => [v.id, v])