我是JavaScript新手,我遇到了问题,我需要从json文件中删除所有空值。但我一直没有得到它我尝试了不同的方法,我发现在网站上,但他们不适合我。 我在下面找到的方法之一。我只是有一个问题,因为我在json文件之前说过,我用JSON.stringify得到它,并使用删除null的代码,我得到这个“{\”name \“:\”Ann \“,\”children \“: [null,{\“name \”:\“Beta \”,\“children \”:[null,null,null]},null]}“。从json文件中删除空值javascript
function Parent(name){
this.name = name;
this.children=new Array(null,null,null);
}
Parent.prototype.getName = function(){
return this.name;
};
Parent.prototype.setName = function(name) {
this.name=name;
};
Parent.prototype.getChildren = function(){
return this.children;
};
Parent.prototype.setChildren = function(parent) {
this.children=parent;
};
var parent = create(aux,new Parent(""));// This method create tree parent
var o = parent;
j = JSON.stringify(o, (k, v) => Array.isArray(v)
&& !(v = v.filter(e => e !== null && e !== void 0)).length ? void 0 : v, 2)
alert (j);
JSON文件:
{
"name": "Ann",
"children":
[
null,
{
"name": "Beta",
"children":
[
null,
null,
null
]
},
null
]
}
我想到:
{
"name": "Ann",
"children":
[
{
"name": "Beta"
}
]
}
因为我不认为你想要删除对象的属性。它看起来像你需要“拼接”数组的空元素。 – Andy
您确定要修改原始对象吗?我会考虑创建一个新的过滤对象,而不是更新和删除原始参考的属性 –
@MatiasCicero Relax,它来自JSON文件,所以一旦它被解析,它已经是一个副本。 – blex