javascript - Node : remove json element in json object

标签 javascript node.js

我想从 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++;
    });

最佳答案

为了使测试数据更加清晰,我在脚本的第 1 行调整了 var M = bot.ids[message.guild.id].members; 以直接从示例数组中提取...

我的解决方案是:

/*
 * 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 执行时(而不是超时内)定义每个超时的“剩余”数组成员。此解决方案假设成员数组在超时执行期间不会添加任何新成员。

关于javascript - Node : remove json element in json object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53585891/

相关文章:

javascript - 如何通过 2D 前景穿透或切孔

补充 Razor MVC 的 Javascript 库

javascript - 如果未设置 key ,则设置 key - 哪种方式最有效?

javascript - 带 Handlebars 的 nodemailer 无法正确显示样式

javascript - root id 中没有呈现任何内容

javascript - 将响应消息从一个客户端发送到另一个 socket.io 时出现问题

javascript - Angular $digest 循环刷新整个 View 而不是一部分

mysql - nodejs和DB之间如何通信

javascript - gulp-rename 进行复制,但不替换

javascript - jsdom 未加载或未在页面中运行外部脚本