Milligran
Milligran

Reputation: 3161

How to remove node from array using javascript

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

Answers (4)

dani
dani

Reputation: 1

You can do this:

myarray.data = myarray.data.filter(function(item) {
  return item.UserId !== 2;
});

Upvotes: 0

gines capote
gines capote

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

Artem Sobolev
Artem Sobolev

Reputation: 6069

There are several possibilies:

  1. Array#splice, but you need to know index of corresponding entry.
  2. 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

joellustigman
joellustigman

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

Related Questions