Vue JS - remove object from data array
I am using VueJS to display active users on a site. When the user becomes active, Pusher sends JSON with their details -
{
"token": "97LbfNs7pfPbzVLo",
"first_name": "Joe",
"last_name": "Smith",
"avatar": "http://demo.com/avatar.jpg",
"phone": "255-255-2555",
"available" : true,
"agencies": [
{
"name": "Some company",
"slug": "some-company"
}
]
}
When a user subscribes, they are token
sent along with available: false
. I need to remove them from my Vue array data
, this is where I am stuck.
Here is an array of data in my Vue JS (pretty basic):
data: {
responders: []
}
UPDATE
Here is the basic idea of what I am trying to accomplish, just from outside Vue methods
. Basically I just need to remove an item from the data array, I think this is more of a Javascript related issue than it is for Vue.
@michaelsnowden made a suggestion to store users as objects instead of an array, but I'm not sure how. I tried:
addUser: function() {
var user = {'asdasdasdop': {name: "Joe"}};
this.users.push(user);
}
Which gives me:
"users": [
{
"asdasdasdop": {
"name": "Joe"
}
}
],
But beyond that, I can't figure out how to access those values or remove an item from the array based on the token. Any help would be greatly appreciated - I had no problem adding, but I can't figure out how to do it.
source to share
Vue augments the traversed arrays with the $ remove method, which takes a numeric index as a parameter. This way you can find the index with something like:
var userToken ='potato';
var tokenToRemove;
users.forEach(function(user, index) {
if(userToken === user.token) {
tokenToRemove = index;
}
});
users.$remove(tokenToRemove);
so that you can somehow find the index of the user with the potato marker and using the $ remove method.
source to share
// hook into pusher
ready: () => {
var self = this;
socket.bind('new-user', (user) => {
self.addUser(user)
})
},
methods: {
addUser: (user) => {
this.users.push(user)
},
deleteUserByToken: (token) => {
var user = this.findByToken(token);
if (user != 'undefined') {
this.users.$remove(user);
} else {
//
}
},
findByToken: (token) => {
this.users.find((usr) => {
return usr.token === token
});
}
}
API reference
source to share