[英]How to filter an array by items from another array
我們正在使用vue和vuex創建一個應用程序。 我們為用戶關注的場所提供了一系列場所ID。 我們希望每個用戶都能看到他們關注的所有場所的清單。
例如:
venues: [
{venue:1, title: Shoreline}
{venue:2, title: Bill Graham}
{venue:3, title: Golden Gate}
{venue:4, title: Orphium}
]
我正在追蹤:[1,3]
但我不想顯示結果1和3。我希望頁面上的結果顯示我正在關注“海岸線”和“金門大橋”
我一直在嘗試使用地圖和過濾器功能,但無法使其正常工作。
getFollowingState({ commit, state }) {
fb.venueFollowersCollection.where("user", "==", state.currentUser.uid).onSnapshot(querySnapshot => {
let followingArray = []
querySnapshot.forEach(doc => {
console.log(doc.data())
let followed = doc.data().venue
followingArray.push(followed)
})
store.dispatch('getUserVenues', followingArray)
commit('setFollowedVenues', followingArray)
})
},
這為我提供了我所關注的場所的所有ID的數組。 doc.data()如下所示:
email: "greg@..."
name: "Gre..."
phone: "925..."
user: "jxckuJwXxRdgfKmEduYlLbfxd1g1"
venue: "S2XWn8tG0tIMyoOyAcuc"
venueName: "California Memorial Stadium"
接下來,我要獲取ID所在的每個場所對象(我要關注的場所的ID數組)(有效載荷)。
getUserVenues({ commit }, payload) {
fb.venuesCollection.onSnapshot(querySnapshot => {
let venuesArray = []
querySnapshot.forEach(doc => {
if ((doc.data()).includes(payload)) {
let venue = doc.data()
venuesArray.push(venue)
console.log(doc.data())
}
})
console.log(venuesArray)
commit("setUserVenues", venuesArray)
})
},
這部分無效,因為“ payload”不是字符串。 我需要做些什么不同的事情?
按另一個數組中的項目篩選數組的最簡單解決方案是使用include()功能:
const venues = [
{venue:1, title: 'Shoreline'},
{venue:2, title: 'Bill Graham'},
{venue:3, title: 'Golden Gate'},
{venue:4, title: 'Orphium'}
];
const following = [1, 3];
const tittles = venues
.filter(item => following.includes(item.venue))
.map(item => item.title);
console.log(tittles);
日期:
['Shoreline','Golden Gate']
我認為您想要的是這樣的:
getUserVenues({ commit }, payload) {
fb.venuesCollection.onSnapshot(querySnapshot => {
const venuesArray = [];
querySnapshot.forEach(doc => {
const venue = doc.data();
if (payload.includes(venue.venue)) {
venuesArray.push(venue);
}
});
commit('setUserVenues', venuesArray);
});
},
這些變量有點令人困惑,因為您的venue
對象具有一個venue
字段,而不是一個id
(至少這就是我解釋您的問題的方式)。 因此,如果venue.venue
是您要在payload
匹配的ID,則payload.includes
payload
venue.venue
是您所需要的。
如果您要提交整個場地對象以外的其他東西,則可以執行以下操作:
只提交名字
commit('setUserVenues', venuesArray.map(v => v.venueName));
只提交名稱和ID
commit('setUserVenues', venuesArray.map(v => ({ id: v.venue, title: v.venueName})));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.