删除数据数组JS

我正在创build一个文件,可以从JSON文件中读取数据。

我可以添加新的名称到文件,但我无法删除。 当我input一个名字来删除它时,实际上是把这个名字添加到这个文件中。

为什么添加和不删除? 目标是能够从列表中删除将生成的特定名称。

先谢谢你! 这是我的代码与我正在尝试做什么的意见。

// 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": "" } ] } 

splice函数从数组中删除项目并返回已删除的项目。 所以,如果你想通过像Full_Name这样的JSON属性来删除一个项目,你必须首先find该项目的索引。

 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是allways -1,因为indexOf不知道要检查哪个属性,只是检查整个对象。

以下代码也必须在上面的代码之后。 (所以在你对json做出任何改变之后)

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

我也build议阅读关于javascriptdebugging的这个turtorial 。 它让你的生活更容易find错误。