I want to change the display of an object (which may have duplicate values). Example:
const city2country = { 'Amsterdam': 'Netherlands', 'Rotterdam': 'Netherlands', 'Paris': 'France' };
reverseMapping(city2country) Should output:
{ 'Netherlands': ['Amsterdam', 'Rotterdam'], 'France': ['Paris'] }
I came up with the following naive solution:
const reverseMapping = (obj) => { const reversed = {}; Object.keys(obj).forEach((key) => { reversed[obj[key]] = reversed[obj[key]] || []; reversed[obj[key]].push(key); }); return reversed; };
But I'm sure there is a neater, shorter path, preferably prototyped, so I could just do:
const country2cities = city2country.reverse();
Thanks.
source share