I have an array of objects where each object has two keys: key (k
) and value (v
). I need to make an object that would take values of k
and collect corresponding values of v
as a value of this key, an array of them.
So, for example, from an array
[{
k: 'a',
v: 0
}, {
k: 'a',
v: 1
}, {
k: 'b',
v: 2
}]
I need an object
{
a: [0, 1],
b: [2]
}
It's easy to use outer-scope variables but what I want to do is to perform it in functional manner.
Right now, I have this piece of (ES6) code:
rows.reduce((result, item) => ({
...result,
[item.k]: [
...(result[item.k] || []),
item.v
]}),
{});
It works nice but the question is if it is possible to optimize it in terms of SLOC. For one, I don't like the ...(result[item.k] || [])
piece but if I leave it as simple as ...result[item.k]
then I get an error because, when it's undefined, babel fails to perform a method call of it, since undefined doesn't have any methods.
Did I maybe take a wrong path and there's a more elegant solution that reducing the array?
I would appreciate any suggestions, please throw any ideas at me.