Javascript 从数组中删除基于条件的记录

Javascript 从数组中删除基于条件的记录,javascript,Javascript,结果: resp = { "result": [ { "name": "john", "value": "he has car" }, { "name": "may", "value": "she has phone"

结果:

resp = {
            "result": [
                {
                    "name": "john",
                    "value": "he has car"
                },
                {
                    "name": "may",
                    "value": "she has phone"
                },
                {
                    "name": "john",
                    "value": "he has car"
                },
                {
                    "name": "may",
                    "value": "she has phone"
                }
            ]
        };

for(i=0;i为什么不简单地使用
Array#filter
?因为处理拼接的方式似乎很复杂,而且看起来是错误的(特别是
.splice(…,2)
,其中两个是要删除的元素数)

const resp={
“结果”:[{
“姓名”:“约翰”,
“价值”:“他有车”
},
{
“姓名”:“可能”,
“价值”:“她有手机”
},
{
“姓名”:“约翰”,
“价值”:“他有车”
},
{
“姓名”:“可能”,
“价值”:“她有手机”
}
]
};
resp.result=resp.result.filter({name,value})=>{
return!(name==“may”&&value.startsWith(“she”))
});
console.log(
相应结果

);
创建一个函数,从数组中删除一个项,然后移动数组的其余部分

 for(i=0; i<resp.result.length;i++){
        if (resp.result[i].name === "may" && resp.result[i].value.startsWith("she")) {
            resp.result[i].splice(resp.result.indexOf(resp.result[i].value) - 1, 2);
            i--;
        }
    }
现在你可以这样使用它

removeArrayElement = function(callback) {
var i = this.length;
while (i--) {
    if (callback(this[i], i)) {
        this.splice(i, 1);
    }
  }
};

尝试递减索引值,无效此代码将删除oly前2条记录,实际结果应为空数组,我的意思是第3条第4条记录(索引2,3)也应得到delete.coz在第4次迭代中的“if”条件将satisfy@chandu你能提供一个你期望的输出的例子吗?结果数组应该是一个empty@chandu您的if条件(如果正确)仅当名称为may且值以she开头时才会筛选值。对于该条件,您的对象john未解析为true。您能否澄清列表如何与您的条件一起为空?根据我的if条件,2条记录将正确筛选?即第2条第4条记录。在我的第一个条件为true时,我将拼接2条记录,因此第三条和第四条记录将保留在数组中。第三条和第四条记录将进入数组中的0,1索引位置。我对吗?根据循环,它将继续查找不存在的第三个索引位置。因此,我将索引值从0递减到循环。
resp = [ {num:1, str:"a"}, {num:2, str:"b"}, {num:3, str:"c"} ];
resp.removeArrayElement( function(item, idx) {
    return item.str == "c";
});