[英]javascript remove previous filter on an object before applying new one
I have a series of buttons that apply filters to an object using a function similar to this: 我有一系列按钮,它们使用类似于以下的功能将过滤器应用于对象:
isNew(type) {
//need to reset filter first
this.results = this.results.filter(function(type) {
return type.has_user_viewed === true
})
console.log('isNew');
}
The problem I have is if one filter is applied by the user clicking, and then another filter applied, the filtered array is filtered again. 我遇到的问题是,如果用户单击应用了一个过滤器,然后又应用了另一个过滤器,则再次过滤已过滤的数组。 What I need to do with the above is reset the object to it's original state before applying a new filter.
我需要做的是在应用新的过滤器之前将对象重置为其原始状态。 Not sure how to "reset" a filter here?
不确定如何在此处“重置”过滤器?
Just save the unfiltered data to a variable. 只需将未过滤的数据保存到变量。
filter
creates a new array object (shallow copying elements) each time, so your code overwrites the original data with the filtered data: filter
每次都会创建一个新的数组对象(浅复制元素),因此您的代码将使用过滤后的数据覆盖原始数据:
this.data = [...whatever the source is]
isNew(type) {
//need to reset filter first
this.results = this.data.filter(function(type) {
return type.has_user_viewed === true
})
console.log('isNew');
}
You'll probably need to store the result of the filter somewhere other than this.results if you want to access the original list of results for additional filtering later. 如果要访问原始结果列表以供以后进行其他过滤,则可能需要将过滤器的结果存储在this.results之外的其他位置。 Note that this change will likely force you to change other code.
请注意,此更改可能会迫使您更改其他代码。
An example of what I'm recommending: 我推荐的示例:
this.filteredResults = this.results.filter(function(type) {
return type.has_user_viewed === true
})
I would suggest that you google immutability, as understanding it will help you greatly when you need to solve similar problems in the future. 我建议您使用Google不变性,因为了解它会在将来需要解决类似问题时极大地帮助您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.