Swap keys and values in a JavaScript object

Let's assume that you have the following object:

javascript
let people = {
    'elon': 10000000000000,
    'bill': 10000000000000,
    'jeff': 10000000000000,
    'erik': 1
}

To reverse keys in values:

javascript
let _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:

javascript
let _people = Object.entries(people).reduce((acc, [key, value]) => (acc[value] = key, acc), {})
// {1: 'erik', 10000000000000: 'jeff'}

Alternatively, mutating the object:

javascript
for (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.