nix9 February 2016

Check the object already exists in array in Vue.js

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?

Answers


nix9 February 2016

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');
}


Peter February 2016

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;
})

Post Status

Asked in February 2016
Viewed 3,131 times
Voted 6
Answered 2 times

Search




Leave an answer