2 回答
TA貢獻1827條經驗 獲得超8個贊
fs.readFile('databases/magistercredentials.json', 'utf-8', function (err, data1) {
if (err) throw err
var magistercreds = JSON.parse(data1)
for (a = 0; a < magistercreds.users.length; a++){
magistercreds.users.splice( a, 1 );
a--; // to step back, as we removed an item, and indexes are shifted
}
但可能你只想更新,所以你可以讓它變得簡單:
fs.readFile('databases/magistercredentials.json', 'utf-8', function (err, data1) {
if (err) throw err
var magistercreds = JSON.parse(data1)
magistercreds.users[68468] = {.....}
TA貢獻1836條經驗 獲得超5個贊
關于是要刪除鍵還是要刪除整個對象的問題尚不清楚。假設要從數組中刪除整個元素users,可以使用拼接方法。
首先使用 找到要刪除的元素的索引findIndex。然后您可以使用splice就地修改數組。
樣本:
fs.readFile('databases/magistercredentials.json', 'utf-8', function (err, data1) {
if (err) throw err
var magistercreds = JSON.parse(data1)
// Assuming you want to delete the element which has the Discordid property as "discid"
var indexOfElement = magistercreds.findIndex(el => el.Discordid === "discid")
magistercreds.users.splice(indexOfElement, 1) // This will remove 1 element from the index "indexOfElement"
}
此外,不需要使用Object.keys來迭代數組。原始問題中的 for 循環可以重寫為:
for (a = 0; a < magistercreds.users.length; a++) delete magistercreds.users[a]
如果這不是您想要實現的,請編輯問題以添加更多信息。
添加回答
舉報
