從網上抓取的Json有大片的空屬性,想直接幹掉精減一下結構。
功能描述
功能如下:
- 屬性值爲空字符串、null、undefined的屬性
- 支持遞歸刪除,即有些空屬性是由於代碼執行中產生的,這些屬性也要刪除
效果演示
檢驗代碼及效果如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | var object = { 'name' : 'Sodino.com', 'pEmpty' : '', 'pNull' : null, 'pUndefined' : undefined, 'pArr' : [], 'pArr1' : [ {} ], 'pObj' : {'arr':[]}, 'pObj1' : { 'ele' : '', 'obj' : {} } }; deleteEmptyProperty(object); var string = JSON.stringify(object); console.log(string); |
控制檯輸出如下:
代碼實現
具體實現代碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | function deleteEmptyProperty(object){ for (var i in object) { var value = object[i]; // sodino.com // console.log('typeof object[' + i + ']', (typeof value)); if (typeof value === 'object') { if (Array.isArray(value)) { if (value.length == 0) { delete object[i]; console.log('delete Array', i); continue; } } deleteEmptyProperty(value); if (isEmpty(value)) { console.log('isEmpty true', i, value); delete object[i]; console.log('delete a empty object'); } } else { if (value === '' || value === null || value === undefined) { delete object[i]; console.log('delete ', i); } else { console.log('check ', i, value); } } } } function isEmpty(object) { for (var name in object) { return false; } return true; } |
2016 05 12 更新日期:2016 05 12
從網上抓取的Json有大片的空屬性,想直接幹掉精減一下結構。
功能描述
功能如下:
- 屬性值爲空字符串、null、undefined的屬性
- 支持遞歸刪除,即有些空屬性是由於代碼執行中產生的,這些屬性也要刪除
效果演示
檢驗代碼及效果如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | var object = { 'name' : 'Sodino.com', 'pEmpty' : '', 'pNull' : null, 'pUndefined' : undefined, 'pArr' : [], 'pArr1' : [ {} ], 'pObj' : {'arr':[]}, 'pObj1' : { 'ele' : '', 'obj' : {} } }; deleteEmptyProperty(object); var string = JSON.stringify(object); console.log(string); |
控制檯輸出如下:
代碼實現
具體實現代碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | function deleteEmptyProperty(object){ for (var i in object) { var value = object[i]; // sodino.com // console.log('typeof object[' + i + ']', (typeof value)); if (typeof value === 'object') { if (Array.isArray(value)) { if (value.length == 0) { delete object[i]; console.log('delete Array', i); continue; } } deleteEmptyProperty(value); if (isEmpty(value)) { console.log('isEmpty true', i, value); delete object[i]; console.log('delete a empty object'); } } else { if (value === '' || value === null || value === undefined) { delete object[i]; console.log('delete ', i); } else { console.log('check ', i, value); } } } } function isEmpty(object) { for (var name in object) { return false; } return true; } |