Search code examples
javascriptjsonsweetalertsweetalert2

Build a JSON structure for key and value pairs, where the keys changes for each item?


I am using SweetAlert2, and I need to create the options which will be populated in a select box for that. I know that I can use the "inputOptions" field for that, however, and I looked at their example (from their site) below :

inputOptions: {
  'SRB': 'Serbia',
  'UKR': 'Ukraine',
  'HRV': 'Croatia'
},

Now, that is great and all, when you have a fixed set of data which is hard coded. However, in my use case, I need to be able to pull these in from a database, and my API does that already via a REST endpoint, and lets say I get it back in the following structure :

[
  {"key": "SRB", "value":"Serbia"},
  {"key": "UKR", "value":"Ukraine"},
  {"key": "SRB", "value":"Croatia"}
]

Is there an easy way to convert the bottom format to the top?

I tried iterating over it, creating a var for each one, as follows :

            var items = JSON.parse(listFromAPI);
            for (var item in items)
            {
              var test = { item.key : item.value };
            }

but that didn't seem to work? I could really use some help here.

Thanks in advance!


Solution

  • You can iterate over your base object and create the inputOptions as you want:

    var base_format = [
      {"key": "SRB", "value":"Serbia"},
      {"key": "UKR", "value":"Ukraine"},
      {"key": "HRV", "value":"Croatia"}
    ];
    
    var inputOptions = {};
    
    for (item of base_format)
      inputOptions[item.key] = item.value;
      
    console.log(inputOptions);