首页 > 解决方案 > 根据数组中的条件删除记录

问题描述

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 条记录。然后无法迭代其余记录。但是仍然存在必须满足“如果”条件的记录。

标签: javascript

解决方案


为什么不简单地使用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
);


推荐阅读