0

I'm wondering if there is a way to clear or empty an array of objects, let's say for example i have this array of objects, which i borrow from firebase firestore, i do this with a snapshot, here is the code:

let siteButtonsData = firebase.firestore()
        .collection('app_settings')
        .doc('dashboard')
        .collection('main_panel')
        .onSnapshot(doc => {
          doc.forEach(doc => {
            this.arrObj.push(doc.data())
          });
        })

Then my array of objects is populated correctly, and it's shown like this:

data() {
    return { 
      arrObj: [
       {
         action: 'one',
         id: 1,
         text: 'hello1'
       },
       {
         action: 'two',
         id: 2,
         text: 'hello2'
       },
       {
        action: 'three',
        id: 3,
        text: 'hello3'
       },
      ]
    }
}

With v-for i iterate over this.buttons to create some dynamic content in my app, but when something changes on my firestore database, and the snapshot updates it, i got duplicates, i was hoping to clear the array of objects before updating from firestore, so i would have no duplicates, but it's not working, so far i have tried:

this.arrObj = [{}]
this.arrObj = [] //This option leaves me with no way to push the array of objects
this.arrObj.length = 0

No matter which of this methods i use, i can't update correctly the array of objects, the first time it does the job well gathering the data from firestore, but once i update the database i got duplicates.

thanks in advance for any help or hint

8
  • have you tried it? what does not work? Commented Jun 18, 2020 at 8:49
  • arrObj = [] or arrObj .length=0 Commented Jun 18, 2020 at 8:49
  • what's the point of doing arrObj = [{}] ? how is that different from arrObj.length=0? Commented Jun 18, 2020 at 8:50
  • @YevgenGorbunkov setting arrObj.length=0 removes all entries from arrObj, whereas arrObj = [{}] overwrites the variable with an array containing a single empty object. All other references to the previous arrObj are not affected from this "update". It's basically the same as restoring your current car to look like new vs buying the same car again. Plus [{}] is not an empty array. Commented Jun 18, 2020 at 8:59
  • @OP given my explanation above, what exactly are you trying to accomplish? Do you want to clear that exact array? Or do you want to "restore" the variable? And what about the empty object at index 0? Commented Jun 18, 2020 at 9:05

2 Answers 2

1

When working with arrays you always need to make sure that Vue's reactivity system is catching the changes and updates the view. Vue is automatically observing some array mutation methods to make sure to update, them being push(), pop(), shift(), unshift(), splice(), sort() and reverse(). See https://v2.vuejs.org/v2/guide/list.html#Mutation-Methods

As for your example, what should work is then:

let siteButtonsData = firebase.firestore()
        .collection('app_settings')
        .doc('dashboard')
        .collection('main_panel')
        .onSnapshot(doc => {
          this.arrObj.splice(0, this.arrObj.length);
          // I would think this works as well:
          // this.arrObj = [];
          doc.forEach(doc => {
            this.arrObj.push(doc.data())
          });
        })
Sign up to request clarification or add additional context in comments.

2 Comments

Worked prefect, whats the second parameter for in the splice? this works for this specific type of data right? for an array of objects
Have a look at this: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Splice takes the first parameter as the start index and then removes as many elements as you give it in the second parameter (by using this.arrObj.lengthit means it removes all elements). This works for arrays of any value, regardless if its an array of objects are other items.
0

What if you want to empty an entire array and just dump all of it's elements?

There are a couple of techniques you can use to create an empty or new array.

The simplest and fastest technique is to set an array variable to an empty array:

var ar = [1, 2, 3, 4, 5, 6];//do stuffar = [];//a new, empty array!

The problem this can create is when you have references to the variable. The references to this variable will not change, they will still hold the original array's values. This of course can create a bug🐛.

This is an over simplified example of this scenario:

var arr1 = [1, 2, 3, 4, 5, 6];var arr2 = arr1; // Reference arr1 by another variable arr1 = [];console.log(arr2); // Output [1, 2, 3, 4, 5, 6]

A simple trick to clear an array is to set its length property to 0.

var ar = [1, 2, 3, 4, 5, 6];console.log(ar); // Output [1, 2, 3, 4, 5, 6]ar.length = 0;console.log(ar); // Output []

Another, sort of unnatural technique, is to use the splice method, passing the array length as the 2nd parameter. This will return a copy of the original elements, which may be handy for your scenario.

var ar = [1, 2, 3, 4, 5, 6];console.log(ar); // Output [1, 2, 3, 4, 5, 6]ar.splice(0, ar.length);console.log(ar); // Output []

The last two techniques don't create a new array, but change the array's elements. This means references should also update.

There is another way, using a while loop. It feels a little odd to me, but at the same time looks fancy, so it may impress some friends!

var ar = [1, 2, 3, 4, 5, 6];console.log(ar); // Output [1, 2, 3, 4, 5, 6] while (ar.length) { ar.pop(); }console.log(ar); // Output []

Not a way I would go about clearing a JavaScript array, but it works and it is readable. Some performance test have also shown this to be the fastest technique, so maybe it is better than I originally thought!

2 Comments

This works with arrays, but not with arrays of objects, i updated my question explaining a lot better what's happening, thanks!
Vue's reactivity system does not catch setting array.length = 0

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.