How to set/update nested object with dynamic keys in Firebase/Vue.js

in Code Write a comment

In this tutorial, you’ll learn how to update the nested object with dynamic keys in Firestore/JavaScript.

In one of my Firebase/Vue.js projects, I needed to update a document with a slightly complex structure by passing keys and values. I was using a Firestore database.

UPDATE_FIELD ({ commit }, payload) {
  return new Promise((resolve, reject) => {
    db.collection('users')
      .doc(user.email).set({
        objectField: {
          nestedField: {
            ourField: passed.value
          }
        } 
      }, {
        merge: true
      })
      .then(snapshot => {
        resolve(snapshot)
      })
  })
}

The goal was to pass some keys with values to a function (Vuex action), which would find those fields in a database and update them.

I ended up with the following solution.

UPDATE_FIELD ({ commit }, payload) {
  return new Promise((resolve, reject) => {
    let objectField = payload.objectField
    let nestedField = payload.nestedField
    let ourField = payload.value
    db.collection('users')
      .doc(user.email).set({
        [objectField]: { // note the square brackets
          [nestedField]: {
            ourField: ourField
          }
        } 
      }, {
        merge: true
      })
      .then(snapshot => {
        resolve(snapshot)
      })
  })
}

Note the square brackets wrapped around the field. This is how we tell Firebase to find and update a field based on a key that was passed.

Without square brackets it will create the following object:

objectField: {
  nestedField: {
    ourField: field.value
  }
}

If you find this post useful, please let me know in the comments below and subscribe to my newsletter. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/firestore-update-nested-object-dynamic-keys

PS: Make sure you check other Firebase tutorials, e.g. How to deploy a Firebase app to multiple environments and How to deploy Vue.js app to Firebase hosting.

Write a Comment

Comment