VueX Getter 从数组中过滤唯一 ID

VueX Getter to filter unique id's from array

我想过滤一个数组(包含对象),以获取包含唯一 correspondence_id 的每条消息。

**存储包含 'messages'(具有此结构):

Getters我要过滤的地方

getCorrespondedUsers: (state) => {
        return state.messages.unique
    }

所有消息都包含一个correspondence_id,但是现在我只能抓取所有消息,但我只想抓取唯一的人。这样做的目的是我有消息,但在左侧我想显示我发消息的每个人(但我不确定如何只能显示每个人一次)。

我如何过滤我的消息以仅 return 每条消息具有唯一 correspondence_id

有一个solution这个问题。

所以你可以这样做:

getCorrespondedUsers: (state) => {
        return state.messages.filter((obj, pos, arr) => {
           return arr.map(mapObj => mapObj["corresponde_id"]).indexOf(obj["corresponde_id"]) === pos;
    });
}

我测试了here

希望有用!

您可以使用 lodash 来保持代码的可读性。示例:

// don't forget to import only what
// you really need, not the whole library
import uniqBy from 'lodash/uniqBy'

export default {
  getCorrespondedUsers: state => uniqBy(state.messages, 'correspondence_id')
}