javascript - 如何从 json 中删除空白字段?
问题描述
所以我得到了一个 json,我必须通过删除所有“空白”字段来清理它。被视为空白的字段是:
- 空数组或对象,
- 带空格的字符串(“”或“”),
null
价值观。
这是我到目前为止所拥有的:
const isBlank = (val) => {
if(val === null ) {
return true
}
if(typeof val === 'string'){
return val.trim().length === 0;
}
return val.length === 0
};
function clean(jsonInput) {
Object.keys(jsonInput).forEach( key => {
if(typeof jsonInput[key] === 'object' && !isEmpty(jsonInput[key])){
clean(jsonInput[key])
}else {
isEmpty(jsonInput[key_field]) && delete jsonInput[key]
}
})
}
这是jsonInput
我正在使用的:
{
"print": "notBlank",
"this": "notBlank",
"example": "notBlank",
"blank": null,
"allBlanks": [
{
"from": "",
"blank0": null
}
],
"att2": {
"blank1": "",
"blank2": []
},
"att3": {
"one": "1",
"two": "2",
"three": "3",
"blank3": " "
}
}
这应该是输出:
{
"print": "notBlank",
"this": "notBlank",
"example": "notBlank",
"att3": {
"one": "1",
"two": "2",
"three": "3"
}
}
相反,我得到了这个:
{
"print": "notBlank",
"this": "notBlank",
"example": "notBlank",
"allBlanks": [{ }],
"att2": {},
"att3": {
"one": "1",
"two": "2",
"three": "3",
}
}
看起来我无法移除物体......有什么想法我做错了吗?有什么办法我可以修复它。
还有一种方法可以做到这一点,这样我就不会更改原始对象,而是制作一个副本,可能使用map
or filter
?
解决方案
这里的主要问题是它[{}]
没有被定义为“空”,因为它是一个长度为 1 的数组,其中有一个对象。但是,因为您希望将空对象视为空对象,从而将具有空对象的数组视为空对象,所以您还需要在isEmpty
函数内部进行递归以覆盖这些角度。
请注意添加到isEmpty
.
至于复制,快速肮脏的方法是首先字符串化然后解析json。您可以在代码底部看到这一行
var jsonCopy = JSON.parse(JSON.stringify(json));
还有更复杂的深度复制方法,请阅读在 JavaScript 中深度克隆对象的最有效方法是什么?了解更多信息。
const isEmpty = (val) => {
if(val === null ) {
return true
}
if(typeof val === 'string'){
return val.trim().length === 0;
}
if(val instanceof Array){
if( val.length === 0 ) return true;
return val.every( v =>
isEmpty(v)
);
}
if(val === Object(val)){
if(Object.keys(val).length == 0) return true;
return Object.values(val).every(
v => isEmpty(v)
);
}
return val.length === 0;
};
function clean(jsonInput) {
Object.keys(jsonInput).forEach( key => {
if(typeof jsonInput[key] === 'object' && !isEmpty(jsonInput[key])){
clean(jsonInput[key])
}else {
isEmpty(jsonInput[key]) && delete jsonInput[key]
}
})
}
var json = {
"print": "notBlank",
"this": "notBlank",
"example": "notBlank",
"blank": null,
"allBlanks": [
{
"from": "",
"blank0": null
}
],
"att2": {
"blank1": "",
"blank2": []
},
"att3": {
"one": "1",
"two": "2",
"three": "3",
"blank3": " "
}
};
var jsonCopy = JSON.parse(JSON.stringify(json));
clean(jsonCopy);
console.log(jsonCopy);
推荐阅读
- javascript - Anki Javascript 代码适用于 Mac Desktop 和 AnkiDroid,但不适用于 Anki(Ipad/Iphone 版本)
- python - 在python代码中实现n-gram用于多类文本分类
- python - 模仿 do while 逻辑控制来处理旋转问题
- android - onChildAdded 调用了两次?
- reactjs - react-admin:如果您将 react-admin 嵌入到非 redux 应用程序中,是否需要将 redux 安装到您的应用程序中?
- r - R Web抓取:提交网站登录表单时出错
- actionscript-3 - 我需要一些关于时钟的建议
- python - Sed 保持匹配过去的换行符
- python - 为什么循环中的赋值语句在python中只执行一次
- typescript - 局部变量不是通过从继承的构造函数调用局部方法来设置的