0

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);
   }
}
6
  • times is firebase array? Commented Jan 3, 2018 at 15:20
  • yea, I get it like this getDayTimes(day: string): FirebaseListObservable<any[]> { const dayPath = ${this.basePath}/${day}; this.times = this.db.list(dayPath); return this.times; } Commented Jan 3, 2018 at 15:23
  • splice will remove item from array but not from firebase Commented Jan 3, 2018 at 15:25
  • How would you go about it, if you wanted it removed from firebase? Commented Jan 3, 2018 at 15:30
  • remove the item and then push the new item Commented Jan 3, 2018 at 15:41

1 Answer 1

2

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];
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hey man, this method feels right to me, maybe I'm not storing the data in the right way. do you have an example fo what the data structure would look like in firebase? I basically have a node called schedule, with a sub-node for each day of the week, the times is what I'm struggling with. thanks in advance
The data would look like the groups node here: firebase.google.com/docs/database/web/structure-data#fanout

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.