2017-12-02 85 views
1

我是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" 
    } 
    ] 
} 
+0

因爲我不認爲你想要刪除對象的屬性。它看起來像你需要「拼接」數組的空元素。 – Andy

+0

您確定要修改原始對象嗎?我會考慮創建一個新的過濾對象,而不是更新和刪除原始參考的屬性 –

+0

@MatiasCicero Relax,它來自JSON文件,所以一旦它被解析,它已經是一個副本。 – blex

回答

2

JSON.parseJSON.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)

+0

你的解決方案是太棒了我只是有一個問題,因爲我在json文件之前說過,我用JSON.stringify獲取它,並使用刪除空數組的代碼:我得到這個「{\」name \「:\」Ann \「,\」children \「:[null,{\」name \「:\」Beta \「,\」children \「:[null,null,null]},null]}」。我究竟做錯了什麼? – pete

+0

@pete也許這些值不是'null',而是'undefined'或丟失。嘗試更新。 – Slai

+0

繼續做同樣的事情是非常奇怪的。隨着JSON燒燬它的作品。但用JSON.stringify獲取它不起作用。 JavaScript只是爲了惹惱我。 – pete