gpt4 book ai didi

Javascript:按值从 Json 中删除元素

转载 作者:行者123 更新时间:2023-11-28 14:38:40 25 4
gpt4 key购买 nike

我需要从 AJAX 调用返回的 json 字符串中删除元素。

我不知道如何循环遍历字符串并删除值为 NULL 的所有元素。

我的 json 看起来像这样。

[
{"ID":"27","Agility":"15","Balance":null,"Strength":"37","Physiology":"32"},
{"ID":"30","Agility":"27","Balance":null,"Strength":null,"Physiology":null},
{"ID":"34","Agility":null,"Balance":null,"Strength":null,"Physiology":null},
{"ID":"36","Agility":null,"Balance":null,"Strength":null,"Physiology":null},
{"ID":"40","Agility":null,"Balance":"20","Strength":null,"Physiology":"34"},
{"ID":"42","Agility":null,"Balance":"16","Strength":null,"Physiology":null},
{"ID":"51","Agility":null,"Balance":null,"Strength":"39","Physiology":null}
]

我想我可以为每个键做这样的事情,但我更喜欢通用函数:

if(json[index].Strength == null){
json.splice(index,1);
}

最佳答案

您可以使用 JSON.parse 方法解析 json,然后对该数组使用 filter() 方法。

const json = '[{"ID":"27","Agility":"15","Balance":null,"Strength":"37","Physiology":"32"},{"ID":"30","Agility":"27","Balance":null,"Strength":null,"Physiology":null},{"ID":"34","Agility":null,"Balance":null,"Strength":null,"Physiology":null},{"ID":"36","Agility":null,"Balance":null,"Strength":null,"Physiology":null},{"ID":"40","Agility":null,"Balance":"20","Strength":null,"Physiology":"34"},{"ID":"42","Agility":null,"Balance":"16","Strength":null,"Physiology":null},{"ID":"51","Agility":null,"Balance":null,"Strength":"39","Physiology":null}]'

const data = JSON.parse(json).filter(o => o.Strength != null)
console.log(data)

如果您想删除某些属性值为 null 的元素,您可以在 filter 中使用 some 方法。

const json = '[{"ID":"27","Agility":"15","Balance":null,"Strength":"37","Physiology":"32"},{"ID":"30","Agility":"27","Balance":null,"Strength":null,"Physiology":null},{"ID":"34","Agility":null,"Balance":null,"Strength":null,"Physiology":null},{"ID":"36","Agility":null,"Balance":null,"Strength":null,"Physiology":null},{"ID":"40","Agility":null,"Balance":"20","Strength":null,"Physiology":"34"},{"ID":"42","Agility":null,"Balance":"16","Strength":null,"Physiology":null},{"ID":"51","Agility":null,"Balance":null,"Strength":"39","Physiology":null}]'

const data = JSON.parse(json).filter(o => {
return !Object.keys(o).some(k => o[k] == null)
})
console.log(data)

关于Javascript:按值从 Json 中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48962043/

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