node.js:删除json对象中的json元素

时间:2018-12-03 00:11:17

标签: 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 个答案:

答案 0 :(得分:0)

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