Let's assume that you have the following object:
javascriptlet people = { 'elon': 10000000000000, 'bill': 10000000000000, 'jeff': 10000000000000, 'erik': 1 }
To reverse keys in values:
javascriptlet _people = {} Object.entries(people).forEach(([key, value]) => _people[value] = key) // {1: 'erik', 10000000000000: 'jeff'}
Despite being more verbose, you could also use a reduce()
function:
javascriptlet _people = Object.entries(people).reduce((acc, [key, value]) => (acc[value] = key, acc), {}) // {1: 'erik', 10000000000000: 'jeff'}
Alternatively, mutating the object:
javascriptfor (let [key, value] of Object.entries(people)) { people[value] = key delete people[key] } // {1: 'erik', 10000000000000: 'jeff'}
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.