如何使用javascript
从以下数组中删除userid 2{"maxPages":2,"data":[{"UserId":"1","UserName":peterparker,"}{"UserId":"2","UserName":spiderman,"}]}
我在考虑首先得到索引: id = 2 row = myarray.data.UserId.indexOf(id)
然后根据索引
删除行答案 0 :(得分: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;
}
}
答案 1 :(得分:0)
有几种可能性:
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 });
答案 2 :(得分: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;
}
}
答案 3 :(得分:0)
你可以这样做:
myarray.data = myarray.data.filter(function(item) {
return item.UserId !== 2;
});