marcelo.wdrb
marcelo.wdrb

Reputation: 2339

Using var in js for cloud firestore

I am using this js code:

var grade_type = document.getElementById("grade_type").value;

gradesRef.set({
          grade_type: firebase.firestore.FieldValue.arrayUnion(grade)
        });  

But in my cloud firestore the field is going to be named with: 'grade_type'. But I want to name the field like the value of grade_type.
How to do that?

Upvotes: 0

Views: 126

Answers (3)

Doug Stevenson
Doug Stevenson

Reputation: 317542

You can set the name of a property with the value of a variable in JavaScript like this:

const fields = {}
fields[grade_type] = firebase.firestore.FieldValue.arrayUnion(grade)

Then pass the object to Firestore:

gradesRef.set(fields)

Upvotes: 0

Vojtech Kane
Vojtech Kane

Reputation: 559

This is not firebase related, you are just looking for a way to write an object literal with variable key in NodeJS. There are plenty of articles explaining that, including this one.

@MrAleister's answer seems to be the easiest one {[variable_name]: value}

Upvotes: 0

MrAleister
MrAleister

Reputation: 1581

gradesRef.set({
      [grade_type]: firebase.firestore.FieldValue.arrayUnion(grade)
    }); 

Upvotes: 2

Related Questions