News for hackers. Stuff that matters.
Re:Deno Joins TC39 by tarjei_huse on Monday December 13, 2021 @09:25AM (#29539818)
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])

Re:Deno Joins TC39 by keville on Monday December 13, 2021 @10:05AM (#29540193)
const foo = bar.reduce((hash, item) => { hash[item.id] = item; return hash; }, {});
Re:Deno Joins TC39 by wiredearp on Monday December 13, 2021 @09:30AM (#29539879)
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 :)

Re:Deno Joins TC39 by wiredearp on Monday December 13, 2021 @10:03AM (#29540179)
Ah yes, true, you always need to map the things ID to the thing itself, so that middle data structure is actually quite annoying :)
Re:Deno Joins TC39 by runarberg on Monday December 13, 2021 @11:23AM (#29541005)

    let foo = Object.fromEntries(bar.map((v) => [v.id, v]));
Re:Deno Joins TC39 by keville on Monday December 13, 2021 @05:15PM (#29545387)
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.
Re:Deno Joins TC39 by runarberg on Monday December 13, 2021 @06:09PM (#29545934)
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.
Re:Deno Joins TC39 by keville on Monday December 13, 2021 @09:06PM (#29547318)
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!