如何使用 javascript 从以下数组中删除用户 ID 2
{"maxPages":2,"data":[{"UserId":"1","UserName":peterparker,"}{"UserId":"2","UserName":spiderman,"}]}
我正在考虑首先获取索引,例如: id = 2 row = myarray.data.UserId.indexOf(id)
然后根据索引删除行
如何使用 javascript 从以下数组中删除用户 ID 2
{"maxPages":2,"data":[{"UserId":"1","UserName":peterparker,"}{"UserId":"2","UserName":spiderman,"}]}
我正在考虑首先获取索引,例如: id = 2 row = myarray.data.UserId.indexOf(id)
然后根据索引删除行
var obj = {}; // ...your object
for ( var i = 0; i < obj.data.length ) {
if ( obj.data[i].UserId == 2 ) {
obj.data.splice(i, 1);
break;
}
}
有几种可能:
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 });
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;
}
}
你可以这样做:
myarray.data = myarray.data.filter(function(item) {
return item.UserId !== 2;
});