Search code examples
javascriptjqueryarrays

Comma-separated list to array and populate dropdown list


I have this dynamic list of countries:

<div>Argentina, Brazil, Colombia, Ecuador</div>

I want to add the countries as options to a combobox dropdown using the following format:

options: [
     { data: 'Argentina' },
     { data: 'Brazil' },
     { data: 'Colombia' },
     { data: 'Ecuador' }
];

I have figured out how to split/join the list items to show the desired array, but not how to populate the dropdown.

https://jsfiddle.net/rj025tkb/

Any help would be appreciated as I've been looking for a solutions for days now. Preferably without using JSON.


Solution

  • This line creates a string in JSON format representing an array of objects.

    "[{data:'" + $(".mycountries").text().split(", ").join("'},{data:'") + "'}]"

    Note that this is a string, not an actual JavaScript array. If you want to create an actual JavaScript array of country objects, you can do it like this by splitting the string and mapping it to objects.

    //Get the comma-separated list of countries
    const countriesString = $(".mycountries").text().trim();
    // Split the string into an array of country names and map each name into an object with the required structure
    const countriesArray = countriesString.split(", ").map(country => {
      return {
        data: country
      };
    });
    // Create a dropdown list widget using that array
    var mydropdown = new OO.ui.ComboBoxInputWidget({
      options: countriesArray
    });
    $("body").prepend(mydropdown.$element);
    $("p").html(JSON.stringify(countriesArray));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://doc.wikimedia.org/oojs-ui/master/demos/node_modules/oojs/dist/oojs.js"></script>
    <script src="https://doc.wikimedia.org/oojs-ui/master/demos/dist/oojs-ui.js"></script>
    <link rel="stylesheet" href="https://doc.wikimedia.org/oojs-ui/master/demos/dist/oojs-ui-wikimediaui.css">
    <script src="https://doc.wikimedia.org/oojs-ui/master/demos/dist/oojs-ui-wikimediaui.js"></script>
    
    <h3>Comma-separated list:</h3>
    <div class="mycountries">Argentina, Brazil, Colombia, Ecuador</div>
    
    <h3>Desired array:</h3>
    <p> </p>