[英]Find matching item across multiple store arrays in VueX
Currently when I want to find single item in an array that is in store I use this:目前,当我想在存储的数组中查找单个项目时,我使用这个:
this.matched = this.$store.state.itemlist.find(itemId=> {
return itemId.id == "someid";
});
Lets says I want to go over multiple arrays to find the matching item given provided ID?让我们说我想遍历多个数组以找到给定 ID 的匹配项? Like i have itemlist1
itemlist2
itemgetter()
... Some of the arrays are getters ( but I think it doesnt change much).就像我有itemlist1
itemlist2
itemgetter()
......一些数组是 getter(但我认为它没有太大变化)。 So basically I want to search over different state and getter items in this component instead of searching over one as in example above.所以基本上我想在这个组件中搜索不同的 state 和 getter 项目,而不是像上面的例子那样搜索一个。
if you just want to find if its exist in one the arrays you can simply write function like this如果您只想查找它是否存在于一个数组中,您可以简单地编写这样的函数
function find(search,...arrs){
return arrs.flat(1).find(item => item == search)
}
this function merge all arrays to one long array and search in it此函数将所有数组合并为一个长数组并在其中搜索
example of usage用法示例
let a=[1,2,3,4]
let b=[5,6,7,8]
let c=[9,10,11,12]
let i=find(6,a,b)
console.log(i)
Using one object to group all the arrays, so that will be possible to iterate over them.使用一个对象对所有数组进行分组,以便可以对它们进行迭代。 The idea is something like below:这个想法是这样的:
const store = new Vuex.Store({
state: {
itemsGroupArrays: {
items1: [{ id: 1, text: "item1 - 1" }, { id: 2, text: "item1 - 2" }],
items2: [{ id: 3, text: "item2 - 1" }, { id: 4, text: "item2 - 2" }]
}
},
getters: {
getItemByIdFromStateGroupArrays: state => (id) => {
let returnedItem = null;
Object.values(state.itemsGroupArrays).forEach((itemStateArray) => {
if (itemStateArray.some(item => item.id === id)) {
returnedItem = itemStateArray.find(item => item.id === id);
}
})
return returnedItem;
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.