0

如何使用 javascript 从以下数组中删除用户 ID 2

{"maxPages":2,"data":[{"UserId":"1","UserName":peterparker,"}{"UserId":"2","UserName":spiderman,"}]}

我正在考虑首先获取索引,例如: id = 2 row = myarray.data.UserId.indexOf(id)

然后根据索引删除行

4

4 回答 4

2
var obj = {}; // ...your object

for ( var i = 0; i < obj.data.length ) {
    if ( obj.data[i].UserId == 2 ) {
        obj.data.splice(i, 1);
        break;
    }
}
于 2013-08-21T18:15:33.633 回答
0

有几种可能:

  1. Array#splice,但您需要知道相应条目的索引。
  2. Array#filter,效率稍低,但更方便:

    var obj = {"maxPages":2,"data":[{"UserId":"1","UserName":peterparker,"}{"UserId":"2","UserName":spiderman,"}]};
    obj.data = obj.data.filter(function(v) { return v.UserId != 2 });
    
于 2013-08-21T18:17:49.433 回答
0

joellustigman 的那个对我有用,但它有两个小的语法更正,i++ 和“==”而不是“=”

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;
    }
}
于 2013-08-21T18:35:02.533 回答
0

你可以这样做:

myarray.data = myarray.data.filter(function(item) {
  return item.UserId !== 2;
});
于 2013-08-21T18:39:48.773 回答