Thursday, 13 April 2017

Javascript - Removing an object from array

I have a JSON file that contains 3 arrays, each with objects inside. The array I am working with is warns. To access the JSON file I use arrayOfObjects and to access my warns array I obviously use arrayOfObjects.warns. I am working with DiscordJS and I want to remove a user from the array based on their user id. user_id = in my JSON file, one of the keys in each object. and user.id is the ID of the user I want to test for.

for (let i = 0; i < arrayOfObjects.warns.length; i++) {
  if (arrayOfObjects.warns[i].user_id === user.id) { // checking if the user has already been warned/in the array.
    message.reply("User has already been warned, now kicking user."); 
    // message.guild.member(user).kick(); // kicks user - commented for testing purposes
    indexOfUser = arrayOfObjects.warns.findIndex(x => x.user_id == user.id); // get the index of the users object
    // console.log(util.inspect(arrayOfObjects.warns[indexOfUser])); // correctly displays the users index within the array
    arrayOfObjects.warns.splice(indexOfUser, 1); // SUPPOSED to remove the user from the array, but doesn't
    return;
  };
};

As you can see from my comment, it doesn't remove the user from the array.



via Rusty

No comments:

Post a Comment