Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
81
rated 0 times [  82] [ 1]  / answers: 1 / hits: 36933  / 8 Years ago, sat, july 23, 2016, 12:00:00

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



enter



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]]



More From » jquery

 Answers
168

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));




[#61276] Wednesday, July 20, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rociom

Total Points: 287
Total Questions: 88
Total Answers: 101

Location: Oman
Member since Wed, Nov 17, 2021
3 Years ago
;