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 条记录。然后无法迭代其余记录。但是仍然存在必须满足“如果”条件的记录。
解决方案
为什么不简单地使用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
);
推荐阅读
- c# - Return only one value from JObject with two values in it C#
- sql-server - 按报表项目计算排序行组
- ios - 找不到 SDK 'iphoneos11.2'
- windows - 如何检查文档是否打开预览窗格
- ssl - MacOS Mojave 更新 SSL/TLS (?) 后无法从“https://rubygems.org/”安装 gems
- css - VS 捆绑发布时出现 CSS 缩小错误
- java - 在for循环SQLite android中迭代游标
- dictionary - Golang map的并发访问如何解决?
- email - Google Analytics - 电子邮件跟踪链接点击 - 如何在同一视图中查看所有自定义活动数据(“发送”、“打开”、“点击”)
- python - LSTM,多二进制数组输入和过拟合处理