2016-12-04 93 views
1

我正在創建一個文件,其中可以從JSON文件中讀取數據。刪除數據數組JS

我可以爲文件添加新名稱,但我無法刪除。當我輸入名稱進行刪除時,實際上會將名稱添加到文件中。

爲什麼要加&不能刪除?目標是能夠從列表中刪除將生成的特定名稱。

預先感謝您!這是我的代碼,對我正在嘗試做的事情發表評論。

// POST request to add to JSON & XML files 
router.post('/post/json', function(req, res) { 

    // Function to read in a JSON file, add to it & convert to XML 
    function appendJSON(obj) { 

     // Read in a JSON file 
     var JSONfile = fs.readFileSync('Staff.json', 'utf8'); 

     // Parse the JSON file in order to be able to edit it 
     var JSONparsed = JSON.parse(JSONfile); 

     // Add a new record into country array within the JSON file  
     JSONparsed.member.push(obj); 

     // Beautify the resulting JSON file 
     var JSONformated = JSON.stringify(JSONparsed, null, 4); 

     // Delte a specific entry from JSON file 
     var i = member.indexOf(" "); 
     if (i != -1) { 
      member.splice(i,1); 
     } 

     // Write the updated JSON file back to the system 
     fs.writeFileSync('Staff.json', JSONformated); 

     // Convert the updated JSON file to XML  
     var XMLformated = js2xmlparser.parse('staff', JSON.parse(JSONformated)); 

     // Write the resulting XML back to the system 
     fs.writeFileSync('Staff.xml', XMLformated); 
    } 

    // Call appendJSON function and pass in body of the current POST request 
    appendJSON(req.body); 

    // Re-direct the browser back to the page, where the POST request came from 
    res.redirect('back'); 
}); 

這裏是JSON文件

{ 
    "member": [ 
     { 
      "Full_Name": "", 
      "Address": "", 
      "Gender": "",  
      "Phone_Number": "" 
     } 
    ] 
} 

回答

1

splice函數從數組中刪除項的一個例子,並返回已刪除的項目。因此,如果您想通過JSON(如Full_Name)中的屬性刪除項目,則必須先找到該項目的索引。

var nameToSearch = "MyName"; 
var itemIndex = -1; 
for(var i = 0; i < JSONparsed.member.length; i++) { 
    if(JSONparsed.member[i].Full_Name === nameToSearch) { 
     itemIndex = i; 
    } 
} 

然後你可以像你一樣刪除項目。

if (itemIndex != -1) { 
    JSONparsed.member.splice(itemIndex,1); 
} 

你最有可能有問題是,itemIndex是-1永諾如indexOf不知道哪個屬性檢查,只是檢查整個對象。

此外,以下代碼必須位於上面的代碼之後。 (因此,任何更改後,您對json

// Beautify the resulting JSON file 
var JSONformated = JSON.stringify(JSONparsed, null, 4); 

我也建議更換閱讀this turtorial關於JavaScript調試。它讓你的生活更容易找到錯誤。

+0

我最好是使用上述還是使用刪除方法? – ThisisD

+0

我的不好,我總是得到拼接和切片混淆。原來'splice'確實在原地修改:) –

+0

splice方法返回「包含已刪除元素的數組」。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice#Return_value – baao