Reputation: 3161
How can I remove userid 2 from the following array using javascript
{"maxPages":2,"data":[{"UserId":"1","UserName":peterparker,"}{"UserId":"2","UserName":spiderman,"}]}
I was thinking of first getting the index like: id = 2 row = myarray.data.UserId.indexOf(id)
Then remove the row based on the index
Upvotes: 0
Views: 104
Reputation: 1
You can do this:
myarray.data = myarray.data.filter(function(item) {
return item.UserId !== 2;
});
Upvotes: 0
Reputation: 1160
The one of joellustigman works for me, but it has two little grammar corrections, the i++ and the "==" instead of "="
var obj = {
"maxPages":2,
"data":[{
"UserId":"1",
"UserName":"peterparker"
},
{"UserId":"2",
"UserName":"spiderman"
}
]}
for ( var i = 0; i < obj.data.length; i++ ) {
if ( obj.data[i].UserId == "2" ) {
obj.data.splice(i, 1);
break;
}
}
Upvotes: 0
Reputation: 6069
There are several possibilies:
Array#filter, which is slightly less efficient, but more convinient:
var obj = {"maxPages":2,"data":[{"UserId":"1","UserName":peterparker,"}{"UserId":"2","UserName":spiderman,"}]};
obj.data = obj.data.filter(function(v) { return v.UserId != 2 });
Upvotes: 0
Reputation: 336
var obj = {}; // ...your object
for ( var i = 0; i < obj.data.length ) {
if ( obj.data[i].UserId == 2 ) {
obj.data.splice(i, 1);
break;
}
}
Upvotes: 2