Search code examples
javascriptnode.jsdiscorddiscord.js

Convert string to object for .SetChoices() Discord.js v14


So I have a string '{ name:"All", value:"All"},{ name:"Home", value:"Home" },{ name:"Coding", value:"Coding" }' but I want to put it in the .SetChoices() for my Discord bot's command. The reason I need this, is because when I edit an external JSON file, it automatically adds values to the Choices for this command. And it also is needed for the command's functionality.

But I need some sort of object to go inside the .SetChoices(). And when I have an array of objects, it doesn't like it and gives an error. I wanted to see if there was a way to convert this string into multiple objects that would be in one variable so I don't have to add new values to both the external JSON and also another object.

Kinda what I want is for one variable to be equal to { name:"All", value:"All" },{ name:"Home", value:"Home" },{ name:"Coding", value:"Coding" } (multiple objects). But I don't know if it is possible.


Solution

  • If you want your objects to be passed into method not as array of objects but as objects themselves, you can use array destruction.

    Just as an example, here how you can use the destruction to pass the arguments and how it will work:

    // You store your choices as array of objects and parse them
    // into array which will look like this one:
    const choices = [
      {name: "All", value: "All"},
      {name: "Home", value: "Home"},
      {name: "Coding", value: "Coding"}
    ];
    
    // Now you just need to add `...` to the beginning of the array
    // in order to destruct it:
    setChoices(...choices);
    
    // Code above is equivalent of you calling the method with objects
    // passed as arguments:
    setChoices(choices[0], choices[1], choices[2]);
    setChoices(
      {name: "All", value: "All"}, 
      {name: "Home", value: "Home"},
      {name: "Coding", value: "Coding"}
    );
    

    All you need is just store the array of choices in JSON, parse it into the array and destruct the following array when passing into setChoices method.