javascript - Check the object already exists in array in Vue.js -
i have data:
data: function() { return { conversations: [ ] } } i'm getting data response object: response.data.conversation
is there way check this.conversations contains response.data.conversation?
to build on answer, if you're using underscore or lodash can use _.any()/_.some() function:
var exists = _.any(this.conversations, function(conversation) { return _.isequal(conversation, response.data.conversation); }) you can use array.prototype.some same kind of thing:
var exists = this.conversations.some(function(conversation) { return _.isequal(conversation, response.data.conversation); }) the benefits of these on solution they'll return find match (instead of iterating through whole array), though update code break out of loop early.
also, while _.isequal() cool, might able away simple property comparisons (if objects flat enough or, better, have key uniquely identifies conversation) determine if 2 objects equivalent:
var exists = this.conversations.some(function(conversation) { return conversation.id === response.data.conversation.id; })
Comments
Post a Comment