Filtering of a table may involve multiple filtering conditions, this.filter
stores an object of the v-model status of all filtering conditions, this.tableData
is an array of all original table data obtained from the backend, this.filteredTableData
is an array of filtered table data.
filterTableData() {
this.filteredTableData = this.tableData.map((item, index) => {
Object.keys(this.filter).forEach(key => {
if (this.filter[key] && item[key] && item[key] === this.filter[key]) {
console.log(item)
return item
}
})
})
console.log(this.filteredTableData)
// this.paginateTableData()
},
Writing like this will make the second console.log(this.filteredTableData)
get an array that is all undefined
. This error should be because forEach cannot use return to break out of the loop.
So I want to know:
How to implement this function when using map and it is best not to use variables inside the map (you can use it, but you are just worried about performance)?
If the amount of data in this.filteredTableData
is particularly large, is there any better way?
Use [].filter directly...
The question is a bit difficult to understand
If you want to convert the map into an array
just enter
[...map]
and that’s itfilter is more appropriate.
Also, where does the idea that adding a variable affect performance come from. Don't rely on guessing that it will have performance problems before any performance problems occur.
Either you use an ordinary for loop instead, or you have to define a bool value outside forEach to judge.
I have encountered problems caused by using map and forEach before, and later solved them by using for...in and for...of reasonably. Can you change your mind and not necessarily use map and forEach to solve it.
Don’t use this in forEach
Let me answer your question where the array is filled with
undefined
.If you don’t have
return
in the map function, of course there will be no return value. The return value that is not displayed is of course undefined.It is equivalent to the result of your traversal not being returned, which is a useless effort.
Shouldn’t the callback function of map be written like this?
Just pretend I didn’t answer and read it again. You know this question. return Object.keys(this.filter) makes no sense to you.
You still need to use an intermediate variable, such as:
I don’t know if that’s what you mean.