javascript - nodejs:删除json对象中的json元素
问题描述
我想从 ids.json 文件中删除一个特定的 ID 我做了一切但没有工作 我不知道问题出在我的代码中
{
"48515607821312": {
"members": [
"23422619525120",
"2861007038851585",
"515129977816704",
"5151310082907392",
"5158931505321230",
"51590130345728"
]
}
}
我的脚本
var M = bot.ids[message.guild.id].members;
var count = 0;
M.forEach(function(id) {
setTimeout(function() {
console.log(id);
delete bot.ids[id];
fs.writeFile('./ids.json', JSON.stringify(bot.ids, null, 4), err => {
if(err) throw err;
});
}, count * 5000)
count++;
});
解决方案
为了清楚测试数据,我var M = bot.ids[message.guild.id].members;
在脚本的第 1 行进行了调整,以直接从示例数组中提取...
我的解决方案是:
/*
* Sample Data
*/
var bot = {
ids: {
"48515607821312": {
"members": [
"23422619525120",
"2861007038851585",
"515129977816704",
"5151310082907392",
"5158931505321230",
"51590130345728"
]
}
}
}
var botObj = bot.ids["48515607821312"] // Replace with bot.ids[message.guild.id] for application
/*
* Loop Thru Members
*/
botObj.members.forEach((id, index) => {
/*
* Create a new array starting at the current index
* thru the end of the array to be used in timeout
*/
var remainingMembers = botObj.members.slice(index, -1)
/*
* Define Timeout
*/
setTimeout(() => {
console.log(id)
/*
* Overwrite bot object with the remaining members
*/
botObj.members = remainingMembers
/*
* Store updated JSON
*/
fs.writeFile('./ids.json', JSON.stringify(bot.ids, null, 4), err => {
if(err) throw err;
});
}, index * 1000)
});
这使用数组索引作为您的替代品,count
并在 forEach 执行而不是在超时内为每个超时定义“剩余”数组成员。此解决方案假定成员数组在执行超时期间不会添加任何新成员。
推荐阅读
- swift - 添加一个 CAShapeLayer 很快就会越界
- c# - 具有用户定义类型的通用方法
- php - 如何将 preg_replace 中的参数传递给 PHP 中的函数?
- javascript - 在 localhost 上部署后的 Vue 应用程序是空白的
- html - 可点击按钮移动另一个选项卡
- javascript - 无法在另一个 .jsp 文件中捕获通过表单输入的值。为什么?
- python - 使用一个数据组的argmax得到另一组的对应数据
- ios - 找不到 -lAFNetworking Xcode 12.4 的库
- vb.net - 将按钮添加到 TreeNode
- vue.js - 为什么 Nuxt 不会自动生成我的静态路由?