Firebase, variable as key name

18,146

Solution 1

For the latest version of Firebase, use brackets around the variable name:

firebase.database().ref("pathName").set({[variable] : 'MoreStuff'});

Using the other method of setting the index of the variable to the value will create an additional layer in the database structure.

Solution 2

Yes. The code is not working as expected because you are using object literal notation, which is the reason the it keeps the variable name as key, because that is how the notation works.

Solution

foo = {}; 
foo[variable] = 'more stuff'; 
fb.set(foo);
Share:
18,146

Related videos on Youtube

Matt Coady
Author by

Matt Coady

Student, Web Developer, Designer, Toast Enthusiast

Updated on June 15, 2022

Comments

  • Matt Coady
    Matt Coady about 2 years

    what I basically want to do is this:

    variable = 'whatever';
    fb.set({ variable : "More Stuff" });
    

    So this will result in an entry that looks like:

    whatever: "More Stuff"
    

    Currently it just ends up as

    variable: "More Stuff"
    

    Can this be done?

    • Ronnie Royston
      Ronnie Royston over 8 years
      In case you are wanting the name of the entry to be variable, simply do var newRef = new Firebase("your-fb-id.firebaseio.com" + variable);
  • Matt Coady
    Matt Coady almost 10 years
    Is x foo in this case?
  • Ronni Skansing
    Ronni Skansing almost 10 years
    @MattCoady yes it was, I changed it to foo ;)
  • WikipediaBrown
    WikipediaBrown over 7 years
    This actually sets a key foo with a value of [variable]: 'more stuff'.
  • Santosh
    Santosh over 6 years
    can I use the same for push method?
  • Andrew Irwin
    Andrew Irwin over 5 years
    Is it ok to use this approach in a very abstract way? i.e where you could have 3 fields in a document, and instead of writing a set method for each field i.e setName, setAge, setDescription, Is it ok to use a method like setData(fieldKey, fieldValue) therefore this saves having to write the same function 3 times, but does it make it difficult for testability or scalability ?
  • mh-cbon
    mh-cbon almost 5 years
    while this might be the correct answer, this is too short for it to be a good answer. Please provide some more details and reference.
  • joshlsullivan
    joshlsullivan almost 4 years
    I read everywhere in the docs. Where did you find this info?
  • vbhaip
    vbhaip almost 4 years
    Honestly, I just tried different ideas that made sense to me until it worked, because I couldn't find anything in the docs either.