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

时间:2019-09-11 22:03:56

标签: javascript arrays vue.js google-cloud-firestore

我们正在使用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”不是字符串。我需要做些什么不同的事情?

2 个答案:

答案 0 :(得分:2)

按另一个数组中的项目过滤数组的最简单方法是使用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']

答案 1 :(得分:2)

认为你想要的是这样的:

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是您所需要的。

如果您要提交除整个场所对象以外的其他内容,可以执行以下操作:

仅输入名称

commit('setUserVenues', venuesArray.map(v => v.venueName));

仅提交名称和ID

commit('setUserVenues', venuesArray.map(v => ({ id: v.venue, title: v.venueName})));
相关问题