简体   繁体   中英

Dynamic naming of .update key Firebase

I have a form where I am uploading many images to different locations, grabbing the downloadURL and using ref.update to store the URL of the image in the correct DB ref.

I'm wondering if it's possible to use a variable in .update to be able to change the key dynamically by grabbing the name of the active file input:

handleImgUpload() {
  var activeInput = document.activeElement.name;
  // set up storage refs, upload file then...
  imgStorageRef.child(filename).getDownloadURL().then(function(url){
    ref.update( {
      activeInput: url // HERE IS WHERE I WANT THE VALUE STORED IN activeInput
})

In this example the ref to be updated will get the string 'activeInput' as the key. Is there a way to add the value that was stored in var activeInput instead?

It sounds like you're trying to dynamically set the property of an object. To do so use [] notation. So:

handleImgUpload() {
  var activeInput = document.activeElement.name;
  // set up storage refs, upload file then...
  imgStorageRef.child(filename).getDownloadURL().then(function(url){
    var updates = {};
    var key = "activeInput";
    updates[activeInput] = url;
    ref.update(updates)
  })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM