Mel Pacheco
Mel Pacheco

Reputation: 799

angularfire2 array manipulation

Whats the correct way to deal with arrays in firebase? I'm trying to toggle a value within an array or numbers when clicking a button. so each number exist only once, say button 12, is clicked, then 12 is added to the array in firebase, if clicked again then it's removed.

this is my code, however, it does not splice, the number is added again every time.

blockTime(time: number) {
const idx = _.indexOf(this.times, time);
if (idx >= 0) {
     this.times.splice(idx, 1);
   } else {

  this.times.push(time);
   }
}

Upvotes: 0

Views: 135

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600100

When you're trying to toggle a value in an array, reconsider your data structure. Whenever you do array.contains(...) or array.indexOf(...) you probably should be using a set-like data structure.

Since JavaScript/JSON doesn't have real sets, you typically emulate them (on Firebase at least) by using an object with true values and your set-items as keys. Then suddenly you operation becomes a lot cleaner:

blockTime(time: number) {
  if (!this.times[time]) {
    this.times[time] = true;
  }
  else {
    delete this.times[time];
  }
}

Or if you're fine with keeping non-blocked time slots with a false value:

blockTime(time: number) {
  this.times[time] = !(this.times[time] || false);
}

Note that when storing this type of data in Firebase, it is best to make sure your keys are strings to avoid the array coercion of the Firebase SDKs. You can simply do this by prefixing the keys with a string, e.g.

blockTime(time: number) {
  var key = "time"+number;
  if (!this.times[key]) {
    this.times[key] = true;
  }
  else {
    delete this.times[key];
  }
}

Upvotes: 2

Related Questions