gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:46:37 24 4
gpt4 key购买 nike

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

最佳答案

为什么不简单地使用Array#filter?因为您处理 splice 的方式看起来很复杂并且看起来错误(特别是 .splice(..., 2) ,其中 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
);

关于javascript - 根据条件从数组中删除记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58376772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com