Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I have a data:

data: function() {
        return {
            conversations: 
            [

            ]
        }
}

I'm getting my data from response object: response.data.conversation

Is there a way to check this.conversations already contains response.data.conversation?

share|improve this question
    
What type of data does this.conversations contain - objects or primitives? If objects, do you have some way to uniquely identify an object? – Peter Feb 8 at 17:59
    
I'm not sure, how can I check it? – nix9 Feb 8 at 18:00
    
@Peter screen -> thats what I got with console.log(this.conversations) – nix9 Feb 8 at 18:03

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;
})
share|improve this answer
1  
Thanks! I would try your solution. – nix9 Feb 9 at 17:37
    
And as you said I have an conversation_id which is unique for each conversation. – nix9 Feb 9 at 17:48

I figured it out:

Used underscore.js.

Iterate trought all objects in array and compare them with _.isEqual(a,b) function

var count=0;

for(var i=0; i<this.conversations.length; i++ ) {
    if(_.isEqual(this.conversations[i], response.data.conversation)) {
        count++;
    }
}

Then check the value of count variable:

if (count == 0) {
    //Add element to array
    this.conversations.push(response.data.conversation); 
} else {
    console.warn('exists');
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.