2

I'm using Vue with Pinia store installed.

export default {
  setup() {
    let rows: Row[] = store.history.rows;
  }
}

This works fine, but later I want to overwrite the array and filter it:

 const filterArray = () => {
      rows=store.history.rows;
       for (let index = 0; index < rows.length; index++){
        if (rows[index].department !== departmentModel.value) {
           rows.splice(index, 1);
        }
      }
    };

Somehow the filterArray method removes the objects from the store.history.rows array as well, so both of the arrays will be empty soon. What I want to archive is every time the filterArray is called, the rows array will be overwritten by the store.history.rows array (which contains all of the objects) and then the rows array will be filtered based on the if statement.

What am I doing wrong?

4
  • is this composition api or options api? (vuejs.org/guide/introduction.html#api-styles) Commented Nov 4, 2022 at 12:16
  • composition api Commented Nov 4, 2022 at 12:19
  • you're making a shallow copy when you need to make a deep copy Commented Nov 4, 2022 at 14:50
  • 1
    @yoduh FWIW, rows=store.history.rows is not a shallow copy but rather reference to the same array. rows = [...store.history.rows] is a shallow copy, which is fine as long as the array items themselves are not getting mutated. Commented Nov 4, 2022 at 19:08

1 Answer 1

4

When you set rows = store.history.rows it doesn't make a copy of the array. It just ends up working like a pointer, referencing the same array.

You can avoid that by making a copy of the array before you proceed mutating it

rows = [...store.history.rows];

Or you use functional conventions, which IMHO is the preferred way anyway.

const filterArray = () => {
  rows = store.history.rows.filter(item => item.department === departmentModel.value)
}

this will create a new array of items that match a given departmentModel.value.

Sign up to request clarification or add additional context in comments.

Comments

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.