从json文件中删除空值javascript
我是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"
}
]
}
回答:
JSON.parse
和JSON.stringify
接受替代品的功能修改值:
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)
以上是 从json文件中删除空值javascript 的全部内容, 来源链接: utcz.com/qa/258574.html