gpt4 book ai didi

javascript - 删除数据数组JS

转载 作者:太空宇宙 更新时间:2023-11-04 00:30:55 25 4
gpt4 key购买 nike

我正在创建一个可以从 JSON 文件读取数据的文件。

我可以向文件添加新名称,但无法删除。当我输入要删除的名称时,它实际上会将名称添加到文件中。

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

提前谢谢您!这是我的代码,其中包含对我正在尝试执行的操作的评论。

// 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 函数从数组中删除项目并返回删除的项目。因此,如果您想通过 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 调试。它使您的生活更容易发现错误。

关于javascript - 删除数据数组JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40959964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com