I find myself doing this many many times and think that it really belongs as a native function on the Array prototype.
If i want to convert an array of recs into a keyed object of the same recs I do this
let ary = [
{id: 'myid1' field1:'abc', field2: 'abc' },
{id: 'myid1' field1:'abc', field2: 'abc' }
]
let oAry = ary.reduce((prev,rec)=> ({...prev,[rec.id] : rec}),{})
Coverting from an array to an object is as ubiquitous as ++ in ones code. As such it should be part of the language.
To accomplish this I have created these two functions that appear to be natural fits for extension to the Array prototype.
Array.prototype.toObjKey = (ary,key , inOjb={})=>
! ary.length || ! key ? inOjb
: ary.reduce((prev,rec,ix)=> ({...prev,[rec[key]] : rec }), inOjb )
Array.prototype.toObjFunc = (ary,func, inOjb={})=>
! ary.length || ! func ? inOjb
: ary.reduce((prev,rec,ix)=> ({...prev,... func(rec,ix,ary) }), inOjb )
These two Array.prototype proposed additions are a natural extension to "Reduce" type functionality that nearly every javascript REST implementation performs .
Low technical risk, low code bloat, easy to understand. What's not to love?