How to change a key in a Firebase database branch

To change a key of a database branch in Firebase, we need to copy the object and then write it again with a different key.

jsx
const changeFirebaseKey = async () => {
    
    // Defining the old and new branches
    let oldBranchRef = firebase.database().ref(`oldBranchKey`);
    let newBranchRef = firebase.database().ref(`newBranchKey`);
    
    // Getting the old object
    let snapshot     = await oldBranchRef.once('value');
    let objectToCopy = snapshot.val();
    
    // Writing object in the new branch and removing the old one
    newBranchRef.set(objectToCopy);
    oldBranchRef.remove();
    
}

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