【发布时间】:2021-09-06 23:00:21
【问题描述】:
所以我要做的是根据另一个数组的内容过滤一个数组,这就是我拥有的代码。
private get filteredArray() {
const filteredArray = this.unfilteredArray;
console.log(this.unfilteredArray);
filteredArray = this.unfilteredArray.filter(
(p) => this.filteredNumbers.includes(p)
);
return filteredArray;
}
例如,我们有两个带有值的数组
this.unfilteredarray = ["1", "2", "4", "3"]
this.filteredNumbers = ["2"]
this.filteredNumbers 从多选框中获取值,因此这里用户选择了2,为此,函数返回的项目是数组filteredArray,其值为"2"。但是,当我随后选择另一个数字进行过滤时,this.filteredNumbers 看起来像 ["2", "3"],那么当我期望返回 2 and 3 时,我仍然只能返回值为 "2" 的 filteredArray。这似乎是因为在console.log 上,我可以看到,当我第二次选择filterNumber 时,unfilteredArray 只剩下"2" 的值,而它仍应保留其所有原始数字 1- 4.我在这里缺少什么或者我应该以其他方式做到这一点?
编辑:正确答案的后续问题 因此,如果我有一个对象,它的所有道具中有 3 个不同的数组,我想将它们全部过滤,然后返回对象本身及其过滤后的数组。有点像这样,但是这个 ofc 不起作用,因为它会弄乱原始数组。或者我需要 3 个不同的 get 吗?
private get filteredObject() {
this.object.unfilteredArray.filter(
(p) => this.filteredNumbers.includes(p)
);
this.object.unfilteredArrayTwo.filter(
(p) => this.filteredNumbers.includes(p)
);
this.object.unfilteredArrayThree.filter(
(p) => this.filteredNumbers.includes(p)
);
return object;
}
【问题讨论】:
标签: javascript arrays vue.js filter