To build on your answer, if you're already using underscore
or lodash
you can use its _.any()/_.some()
function:
var exists = _.any(this.conversations, function(conversation) {
return _.isEqual(conversation, response.data.conversation);
})
You can also use Array.prototype.some
to do the same kind of thing:
var exists = this.conversations.some(function(conversation) {
return _.isEqual(conversation, response.data.conversation);
})
The benefits of these over your solution is that they'll return as soon as they find a match (instead of iterating through the whole array), though you could easily update your code to break out of the loop early.
Also, while _.isEqual()
is cool, you might be able to get away with some simple property comparisons (if your objects are flat enough or, even better, you have a key that uniquely identifies a conversation) to determine if two objects are equivalent:
var exists = this.conversations.some(function(conversation) {
return conversation.id === response.data.conversation.id;
})
this.conversations
contain - objects or primitives? If objects, do you have some way to uniquely identify an object? – Peter Feb 8 at 17:59console.log(this.conversations)
– nix9 Feb 8 at 18:03