我试图简单地创建一个删除函数,以简单地删除 JSON 文件中找到的条目。
到目前为止,下面成功找到了我想要删除/删除
的行(即条目),或者用空白""
更新 - 但是我遇到了困难是时候将其写回到 JSON 文件已删除...它获取得很好,而且我找到了我想要删除的行。
我相信这是一个 JavaScript 问题,也是我在这里处理不当的问题,因为我正在使用 ../processor.php
将新条目写入 JSON 文件。
// Delete Function
dele.addEventListener('click', ()=>{
let e= document.getElementById("dropdown-of-entry");
let slctn= e.value;
console.log(slctn);
fetch(urld)
.then(
function(response) {
response.json().then(function(data) {
let gData = JSON.stringify(data)
let jsonF = JSON.parse(gData);
let findtempto;
let jsonUpdt;
let jsonUpdtd;
for (let i = 0; i < jsonF.length; i++) {
findtempto = jsonF[i].styleName;
if (findtempto === slctn) {
console.log(jsonF[i]); // This successfully finds the line I want to delete
//delete jsonF[i]; // No avail
jsonF[i] = " "; // Am trying this next
// I have also tried moving the ajax call here, and lines above it
}
}
});
jsonUpdt = JSON.stringify(jsonF);
console.log(jsonUpdt);
jsonUpdtd = JSON.parse(jsonUpdt);
console.log(jsonUpdtd);
$.ajax({
url: './php/data/processor.php',
type: 'POST',
data: { template: jsonUpdtd },
success: function(msg) {
console.log('updated/deleted data');
}
});
}
)
.catch(function(err) {
console.error('Fetch Error -', err);
});
});
最佳答案
使用array.filter()
将符合条件的元素保留在数组中。
jsonF = jsonF.filter(e => e.styleName != slctn);
用像 ""
这样的字符串替换对象会在稍后引起问题,因为代码的其余部分期望数组包含对象。
关于javascript - 删除条目或更新为空白(即 "")到 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60837884/