4 ms·
I miss being able to create a hash from an array in a quick way. You always end up with let bar = [{id: zz, }, {id: y},...] let foo = {} bar.forEach(v => foo
by tarjei_huse 5y ago
I miss being able to create a hash from an array in a quick way. You always end up with
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])
- wiredearp 5y agonew Map([[k1,v1], [k2, v2]]) can do that. Or Object.fromEntries with the same argument.
- tarjei_huse 5y agoThanks! You still need to create the middle datastructure ( [[k1,v1], [k2, v2]] ) but it is an improvement :)
- wiredearp 5y agoAh yes, true, you always need to map the things ID to the thing itself, so that middle data structure is actually quite annoying :)
- keville 5y agoconst foo = bar.reduce((hash, item) => { hash[item.id] = item; return hash; }, {});
- runarberg 5y agolet foo = Object.fromEntries(bar.map((v) => [v.id, v]));
- keville 5y agoIt 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.
- runarberg 5y agoObject.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.
- keville 5y agoPlease see my other comment in this thread for the `reduce`-based solution that requires no extra data structures. They're not that hard to get rid of!