Javascript 防止将对象添加到已存在的数组中
我有一个调用Javascript 防止将对象添加到已存在的数组中,javascript,vuejs2,Javascript,Vuejs2,我有一个调用fetchGames函数的输入字段: fetchGames: debounce(function (searchQuery) { this.gallery.forEach((item, index) => { if (item.Key.includes(searchQuery)) { this.filteredGallery.push(item.Key) } else { this.filteredGallery.splice(ind
fetchGames
函数的输入字段:
fetchGames: debounce(function (searchQuery) {
this.gallery.forEach((item, index) => {
if (item.Key.includes(searchQuery)) {
this.filteredGallery.push(item.Key)
} else {
this.filteredGallery.splice(index, 1)
}
})
}, 500)
这类工作。Mygallery
array his 3个对象:
gallery: ['bali', 'brass', 'eclipse']
当我键入a
时,它将bali
和brass
添加到filterGallery
数组中
当我向输入中添加l
(使al
)时,该函数会按预期从数组中删除brass
,但它会向数组中添加另一个bali
,因为项。键
也包括al
如何防止向数组中已存在的数组添加对象
注:使用Vue2时,您不能在Set对象(afaik)上使用
v-for
。您可以在每次输入更改中删除您的arr,或者添加另一个if语句,该语句将检查filteredGallery,并且不会按照其他注释推送它已准备就绪的包含的项目,Set就可以做到这一点。您可以使用以下模式来确保生成的数组不会包含重复项
[…新设置([…CurrentValue,newValue])]
请注意集合是如何分散到一个数组中的,因此您应该可以根据OP提供的代码使用
v-for
,并考虑到这些限制,一种方法是始终对filteredGallery
进行变异。每次搜索时,首先通过将数组的长度设置为零来清空/重置数组。然后,通过提供刚刚清空的filteredGallery
作为回调收集数组,减少gallery
数组,并将其推入新搜索的所有匹配项中
fetchGames: debounce(function (searchQuery) {
this.filteredGallery.length = 0; // reset.
this.gallery.reduce((arr, { Key }) => {
if (Key.includes(searchQuery)) {
arr.push(Key); // push into collector.
}
return arr;
}, this.filteredGallery); // collector.
}, 500)
为了证明建议的方法,上面提供的代码被稍微更改为可执行代码段
函数fetchGamesAtBoundComponent(searchQuery){
this.filteredGallery.length=0;//重置。
this.gallery.reduce((arr,{Key})=>{
if(关键字包括(搜索查询)){
arr.push(键);//推入收集器。
}
返回arr;
},this.filteredGallery);//收集器。
}
常数分量={
画廊:[
{键:'巴厘岛'},
{键:'黄铜'},
{Key:'eclipse'},
],
filteredGallery:['foo','bar','baz'],
};
康斯特小游戏=
fetchGamesAtBoundComponent.bind(组件);
console.log(
“默认状态…”,
{component}
);
游戏(‘a’);
console.log(
“fetchGames('a')…”,
{component}
);
电子游戏(“al”);
console.log(
“fetchGames('al')…”,
{component}
);代码>
.as console wrapper{min height:100%!important;top:0;}
首先,将数组映射为仅包含键属性,然后按包含特定子字符串的属性进行筛选
此处的示例脚本:
this.filteredGallery=this.gallery.map((项)=>item.Key.filter((项)=>item.includes(searchQuery))
是的,我考虑过这个问题,但是我会在一个循环中创建一个循环,这个循环不是很好。清除数组是一个选项。尝试使用Set
而不是array
,这样您就可以调用Set。添加而不必担心重复。您只需使用Set
或添加另一个if
语句来检查该字符串是否已在filteredGallery中。就我个人而言,我会将其缩短,并将其与include一起使用filter,比如this.filteredGallery=this.gallery.map((item)=>item.Key)。filter((item)=>item.includes(searchQuery))
也许我应该说我正在使用Vue2在filteredGallery
中循环,而且看起来你无法通过设置的对象进行v-for操作。谢谢@DominikMatis,这真是个好主意。Smart可以映射和过滤结果,并将其返回到数组变量。如果你想把它写进一个答案,我很乐意接受。我只想为这个画廊创建一个控制it@PeterBoomsma ... 关于最近提供的数组变异方法,还有什么问题吗?似乎Set不适用于Vue2。无法将v-for与集合对象一起使用。您将集合分散到一个数组中,这样就不重要了。@PeterBoomsma。。。关于上述方法还有什么问题吗?