Reputation: 693
I want to filter an array (that contains objects), to grab each message that contains a unique correspondence_id
.
**Store contains 'messages' (with this structure):
Getters where I want to filter it.
getCorrespondedUsers: (state) => {
return state.messages.unique
}
The messages all contain a correspondence_id
, however now I can only grab all the messages, but I want to just grab unique people. The purpose of this is that I have messages, but on the left I want to display each person that I've messaged (but I'm not sure how I can only display each person once).
How can I filter my messages to just return each message with a unique correspondence_id
?
Upvotes: 1
Views: 1632
Reputation: 2489
You can use lodash to maintain readability of your code. Example:
// 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')
}
Upvotes: 3
Reputation: 2105
There is a solution of this problem.
So you can do this:
getCorrespondedUsers: (state) => {
return state.messages.filter((obj, pos, arr) => {
return arr.map(mapObj => mapObj["corresponde_id"]).indexOf(obj["corresponde_id"]) === pos;
});
}
I tested here.
I hope it works!
Upvotes: 2