-1

I am sending data to firebase with the following piece of code which is working:

var mac = "10:10:10:10";
var ref = rootRef.child('user/' + 'nicolas');

if(pass == "4920" ){
 ref.update({
   1: mac
 });
}  

What I need to do is replace the '1' with a variable, since I need to change the value dinamically. I tried the following:

var mac = "10:10:10:10";
var ref = rootRef.child('user/' + 'nicolas');
var index = 1;

if(pass == "4920" ){
 ref.update({
   index: mac
 });
}  

But the result is that the mac address is stored inside "index" directory, and no the directory called "1". Thanks.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Does this answer your question? [How to use a variable for a key in a JavaScript object literal?](https://stackoverflow.com/questions/2274242/how-to-use-a-variable-for-a-key-in-a-javascript-object-literal) Also see [JavaScript set object key by variable](https://stackoverflow.com/questions/11508463/javascript-set-object-key-by-variable) and [Add a property to a JavaScript object using a variable as the name](https://stackoverflow.com/questions/695050/add-a-property-to-a-javascript-object-using-a-variable-as-the-name). – showdev Mar 30 '20 at 19:30

2 Answers2

1

Realtime Database doesn't really have "directories". It has nested nodes. If you want to continue nesting more nodes under ref, you can just keep adding them on with calls to child().

var ref = rootRef.child('user/' + 'nicolas');
var indexRef = ref.child('1');
indexRef.update(mac);

If you want to pass an object with a key that has a value of a varible, you can use JavaScript syntax for that (which has nothing to do with Firebase):

ref.update({
   [index]: mac
});
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
1

Just put the variable name within brackets and it will parse as the actual variable

if(pass == "4920" ){
      ref.update({
      [index]: mac
    });
   } 
sudovert
  • 69
  • 5