13

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

Phiter
  • 14,570
  • 14
  • 50
  • 84

4 Answers4

27

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));
Amit
  • 45,440
  • 9
  • 78
  • 110
4
Object.assign(
  {},
  ...['value1', 'value2', 'value3', 'value4', 'value5'].map((value) => ({
    [value]: value,
  })),
)

returns

{value1: "value1", value2: "value2", value3: "value3", value4: "value4", value5: "value5"}

No common ESlint rules error.

onlyurei
  • 439
  • 5
  • 12
3

if you are using jQuery;

$.extend({}, ['x', 'y', 'z']);

if you not;

Object.assign({}, my_array);

Another example;

var arr = [{
  name: 'a',
  value: 'b',
  other: 'c'
}, {
  name: 'd',
  value: 'e',
  other: 'f'
}];

const obj = arr.reduce((total, current) => {
  total[current.name] = current.value;
  return total;
}, {});

console.log(obj);
Mo.
  • 26,306
  • 36
  • 159
  • 225
Cem Arguvanlı
  • 643
  • 10
  • 15
  • 2
    this does not answer OP's question, it produces an object with numbered keys, instead of the keys being equal to the value – bpylearner Jul 02 '19 at 11:01
2

The key to this is that you can assign properties using the obj["string"] technique:

function ArrayToObject(arr){
    var obj = {};
    for (var i = 0;i < arr.length;i++){
        obj[arr[i]] = arr[i];
    }
    return obj
}
user3163495
  • 2,425
  • 2
  • 26
  • 43