Anthony Mayfield Anthony Mayfield - 4 months ago 34
Javascript Question

How to rearrange data format using lodash

I have some data in the format:

{ regionalGames1: [ 1, 2, 3, 4, 5 ],
regionalGames2: [ 2, 3, 4, 5, 6 ],
regionalGames3: [ 3, 5, 5, 6, 7 ] }


How could I use lodash to rearrange this data to:

{
1: [regionalGames1],
2: [regionalGames1, regionalGames2],
3: [regionalGames1, regionalGames2, regionalGames3],
4: [regionalGames1, regionalGames2, regionalGames3],
...
}


and so on?

I'm looking at
_.groupBy
and also
_.keyBy
but can't seem to figure it out.

Answer

You can do this with Object.keys() and two forEach() loop

var obj = {
  regionalGames1: [1, 2, 3, 4, 5],
  regionalGames2: [2, 3, 4, 5, 6],
  regionalGames3: [3, 5, 5, 6, 7]
}

var result = {}
Object.keys(obj).forEach(function(e) {
  obj[e].forEach(function(a) {
    (!result[a]) ? result[a] = [e] : result[a].push(e);
  });
});

document.body.innerHTML = '<pre>' + JSON.stringify(result, 0, 4) + '</pre>';