Rename an object key in JavaScript

Let's assume that you want to rename a JavaScript object key:

javascript
const renameKey = (object, $old, $new) => {

    let _object = {}

    Object.keys(object).forEach($key => {

        if($key === $old)
            _object[$new] = object[$key]
        else
            _object[$key] = object[$key]

    })

    return _object

}

In this example, I'm using the $ before the variables because I want to avoid using the forbidden word new. I don't like to use oldKey and newKey as variable names because it adds a lot of text to the solution and misaligns the lines of code.

You can use reduce() instead of a forEach() loop, but it's not as legible as using a simple forEach() loop, in my opinion.

Let's try it using the following example:

javascript
let erik = {age: 31, city: "Barcelona", occupation: "Engineer"}

let _erik = renameKey(erik, "city", "location")

// {age: 31, location: "Barcelona", occupation: "Engineer"}

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.