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);
Related videos on Youtube
Comments
-
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 over 8 yearsIn 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 almost 10 yearsIs x foo in this case?
-
Ronni Skansing almost 10 years@MattCoady yes it was, I changed it to foo ;)
-
WikipediaBrown over 7 yearsThis actually sets a key
foo
with a value of[variable]: 'more stuff'
. -
Santosh over 6 yearscan I use the same for push method?
-
Andrew Irwin over 5 yearsIs 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 almost 5 yearswhile 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 almost 4 yearsI read everywhere in the docs. Where did you find this info?
-
vbhaip almost 4 yearsHonestly, I just tried different ideas that made sense to me until it worked, because I couldn't find anything in the docs either.