猿问

删除/更新 node.js 中的 JSON 键

我正在尝试更新或删除(然后重写)node.js 中的 JSON 密钥


JSON:


{"users":[{"Discordid":"discid","Username":"user","Password":"pass","School":"schoolname"}, {"Discordid":"discid1","Username":"user1","Password":"pass1","School":"schoolname1"}]}

我想{"Discordid":"discid","Username":"user","Password":"pass","School":"schoolname"} 通过for 循环删除整个内容,因此我使用变量,该变量a等于我要删除的数据的数量。


我努力了:


fs.readFile('databases/magistercredentials.json', 'utf-8', function (err, data1) {

     if (err) throw err

     var magistercreds = JSON.parse(data1)

     for (a = 0; a < Object.keys(magistercreds.users).length; a++) delete magistercreds.users[a]

和其他一切都不起作用的事情。


翻过高山走不出你
浏览 244回答 2
2回答

斯蒂芬大帝

fs.readFile('databases/magistercredentials.json', 'utf-8', function (err, data1) {&nbsp; &nbsp; &nbsp;if (err) throw err&nbsp; &nbsp; &nbsp;var magistercreds = JSON.parse(data1)&nbsp; &nbsp; &nbsp;for (a = 0; a < magistercreds.users.length; a++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; magistercreds.users.splice( a, 1 );&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a--; // to step back, as we removed an item, and indexes are shifted&nbsp; &nbsp; &nbsp;}但可能你只想更新,所以你可以让它变得简单:fs.readFile('databases/magistercredentials.json', 'utf-8', function (err, data1) {&nbsp; &nbsp; &nbsp;if (err) throw err&nbsp; &nbsp; &nbsp;var magistercreds = JSON.parse(data1)&nbsp; &nbsp; &nbsp;magistercreds.users[68468] = {.....}

一只甜甜圈

关于是要删除键还是要删除整个对象的问题尚不清楚。假设要从数组中删除整个元素users,可以使用拼接方法。首先使用 找到要删除的元素的索引findIndex。然后您可以使用splice就地修改数组。样本:fs.readFile('databases/magistercredentials.json', 'utf-8', function (err, data1) {&nbsp; &nbsp; &nbsp;if (err) throw err&nbsp; &nbsp; &nbsp;var magistercreds = JSON.parse(data1)&nbsp; &nbsp; &nbsp;// Assuming you want to delete the element which has the Discordid property as "discid"&nbsp; &nbsp; &nbsp;var indexOfElement = magistercreds.findIndex(el => el.Discordid === "discid")&nbsp; &nbsp; &nbsp;magistercreds.users.splice(indexOfElement, 1) // This will remove 1 element from the index "indexOfElement"&nbsp;}此外,不需要使用Object.keys来迭代数组。原始问题中的 for 循环可以重写为:for (a = 0; a < magistercreds.users.length; a++) delete magistercreds.users[a]如果这不是您想要实现的,请编辑问题以添加更多信息。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答