Convert javascript array to object of same keys/values

Phiter picture Phiter · Jul 23, 2016 · Viewed 28.3k times · Source

I have a function that returns an array, as follows:

enter image description here

But I'm trying to populate a SweetAlert2 dialog.

As the documentation exemplifies, the desired input would look like this

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

How could I convert my array to the needed format, considering that the key will be the same as the value?

So, something like this would be the result:

{
    'aaa123': 'aaa123',
    'Açucena': 'Açucena',
    'Braúnas': 'Braúnas',
    [...]
}

I have tried JSON.stringify, but the output is not what I need:

"[["aaa123","Açucena","Braúnas","C. Fabriciano","gege","gegeq2","Ipatinga","Joanésia","Mesquita","Rodoviário","teste","teste2","Timóteo","Tomatoentro","ts"]]"

Answer

Amit picture Amit · Jul 23, 2016

This can be done with a simple reduce call:

// Demo data
var source = ['someValue1', 'someValue2', 'someValue3', 'other4', 'other5'];


// This is the "conversion" part
var obj = source.reduce(function(o, val) { o[val] = val; return o; }, {});


// Demo output
document.write(JSON.stringify(obj));