gpt4 book ai didi

javascript - 如何按另一个数组中的项目过滤数组

转载 作者:搜寻专家 更新时间:2023-10-30 22:32:39 25 4
gpt4 key购买 nike

我们正在使用 vue 和 vuex 创建一个应用程序。我们有一组用户关注的场所的场所 ID。我们希望每个用户都能看到他们正在关注的场所的所有 TITLES 列表。

例如:

venues: [
{venue:1, title: Shoreline}
{venue:2, title: Bill Graham}
{venue:3, title: Golden Gate}
{venue:4, title: Orphium}
]

我正在关注:[1, 3]

但我不想显示结果 1 和 3。我希望页面上的结果显示我正在跟踪“海岸线”和“金门大桥”

我一直在尝试使用 map 和过滤器功能,但无法正常工作。

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"

接下来,我想获取每个 field 对象,其中 ID 在我关注的 field 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”不是字符串。我需要做哪些不同的事情?

最佳答案

通过另一个数组中的项目过滤数组的最简单解决方案是使用 includes() 函数:

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' ]

关于javascript - 如何按另一个数组中的项目过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57897376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com