简体   繁体   中英

nodejs: remove json element in json object

I want to remove a specific ID from the ids.json file I did everything but did not work I do not know where the problem is in my code

{
    "48515607821312": {
        "members": [
            "23422619525120",
            "2861007038851585",
            "515129977816704",
            "5151310082907392",
            "5158931505321230",
            "51590130345728"
        ]
    }
}

my script

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

For the sake of clarity with the test data, I have adjusted var M = bot.ids[message.guild.id].members; on line 1 of your script to pull directly from the sample array...

My solution would be:

/*
 * 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)
});

This uses the array index as a replacement for your count and defines the "remaining" array members for each timeout at the forEach execution instead of within the timeout. This solution assumes that the members array will not have any new members added during the execution of the timeouts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM