我是javascript的新手,我遇到了一个问题,我需要从json文件中删除所有空值。但我无法得到它我尝试过在网站上找到的不同方法,但它们对我不起作用。 我在下面找到的方法之一。我只是遇到一个问题,就像我在json文件之前所说的那样,我用JSON.stringify获取它并使用删除null的代码我得到了这个" {\"姓名":\"安\" ,\"儿童\":[null,{\"姓名":\" Beta \",\"儿童\&# 34;:[null,null,null]},null]}"。
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"
}
]
}
答案 0 :(得分:2)
JSON.parse
和JSON.stringify
接受replacer函数来修改值:
j = '{ "name": "Ann", "children": [ null, { "name": "Beta", "children": [ null, null, null ] }, null ] }'
o = JSON.parse(j, (k, v) => Array.isArray(v) ? v.filter(e => e !== null) : v )
console.log( o )

o = { "name": "Ann", "children": [ null, { "name": "Beta", "children": [ null, null, null ] }, null ] }
j = JSON.stringify(o, (k, v) => Array.isArray(v) ? v.filter(e => e !== null) : v, 2 )
console.log( j )

要删除空数组:
o = { "name": "Ann", "children": [ null, { "name": "Beta", "children": [ null, null, null ] }, null ] }
j = JSON.stringify(o, (k, v) => Array.isArray(v)
&& !(v = v.filter(e => e)).length ? void 0 : v, 2 )
console.log( j )