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.row
s 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?
CodePudding user response:
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
.