首页 > 解决方案 > 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++;
    });

标签: javascriptnode.js

解决方案


为了清楚测试数据,我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 执行而不是在超时内为每个超时定义“剩余”数组成员。此解决方案假定成员数组在执行超时期间不会添加任何新成员。


推荐阅读