Hacker News new | ask | show | jobs
by tarjei_huse 1648 days 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])

3 comments

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.
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.
Please 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!