简体   繁体   中英

Firebase, variable as key name

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?

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.

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);

Turns out that @randomnamehere 's command didn't quite deliver what I expected, since I wanted to use a accumulated number - or in your case, a named index - inside a reference while still keeping multiple indexes. So the proper command should have actually been

firebase.database().ref(`pathName/${variable}`).set('More Stuff');

His original answer would actually replace the entire reference with a single named index inside it. I know because I learned it the hard way :P

You can create an Empty object and set your variable as it's property and assign a value to it. Please see below:

let object: any = {};
 object[variable] = value

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