根据条件从数组中删除记录

时间:2019-10-14 12:24:44

标签: javascript

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<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--;
        }
    }

一旦满足“ if”条件,则从数组中拼接前2条记录。然后无法迭代其余记录。 但仍然存在必须满足“如果”条件的记录。

2 个答案:

答案 0 :(得分:1)

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

const 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"
    }
  ]
};

resp.result = resp.result.filter(({name, value})=>{
  return !(name === "may" && value.startsWith("she"))
});

console.log(
  resp.result
);

答案 1 :(得分:0)

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

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

现在您可以像这样使用它,

resp = [ {num:1, str:"a"}, {num:2, str:"b"}, {num:3, str:"c"} ];
resp.removeArrayElement( function(item, idx) {
    return item.str == "c";
});