2017-01-12 82 views
0

我需要在nodeJS中刪除所有具有兩個點或具有空白或空的鍵。刪除鍵匹配一些標記

我有這樣的JSON:

{ 
    "cmd": [ 
     { 
      "key:test": "False", 
      "id": "454", 
      "sales": [ 
       { 

        "customer_configuration": { 
         "key:points": "test value", 
         "": "empty key", 
         "some_field": "test" 
        } 
       } 
      ] 
     } 
    ] 
} 

目標JSON:

{ 
    "cmd": [ 
     { 
      "id": "454", 
      "sales": [ 
       { 
        "customer_configuration": { 
         "some_field": "test" 
        } 
       } 
      ] 
     } 
    ] 
} 

請問您有什麼propsitions?

問候

+1

的'JSON.stringify()'可以過濾的串行化性質的第二個參數。 – Sirko

+0

謝謝@Sirko它的工作原理。 –

回答

4

您可以使用for...in循環來搜索您的數據,然後delete特定屬性的遞歸函數。

var obj = { 
 
    "cmd": [{ 
 
    "key:test": "False", 
 
    "id": "454", 
 
    "sales": [{ 
 

 
     "customer_configuration": { 
 
     "key:points": "test value", 
 
     "": "empty key", 
 
     "some_field": "test" 
 
     } 
 
    }] 
 
    }] 
 
} 
 

 
function deleteKeys(data) { 
 
    for (var i in data) { 
 
    if (i.indexOf(':') != -1 || i == '') delete data[i] 
 
    if (typeof data[i] == 'object') deleteKeys(data[i]); 
 
    } 
 
} 
 

 
deleteKeys(obj) 
 
console.log(obj)

+0

如果你想保留原始對象,並在你的函數中創建新的對象,你應該檢查這個問題http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone- an-object-in-javascript –

+0

謝謝Nenad它的工作原理,我試過JSON.stringify(obj)它也可以工作 –

+0

不客氣。 –