justColbs justColbs - 29 days ago 5
Javascript Question

Node Javascript - string variable setting to literal instead of its' value

I'm playing around with a Node server and having trouble setting values in Firebase with a provided String.

The issue: When I try to set the value of the

carId
variable in the first line of the for loop, it is set as
carId: true
rather than the expected behavior -->
exampleCardId12345: true
.

Why is the value being set to
carId
rather than the value of the
carId
variable, which I set prior to the for loop?

db.ref('/cars').once("value", function(snapshot) {
snapshot.forEach(function(data) {
var carId = data.key;
var drivers = data.val().drivers;
for(key in drivers) {
db.ref('/carsById/'+key).set({carId: true});
}
});
});

Answer

If you want to use a variable's value for a key, use the computed property name syntax:

db.ref('/carsById/'+key).set({ [carId]: true });
                               ^     ^
Comments