Convert javascript array to object of same keys/values

Solution 1:

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

Solution 2:

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.

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

Solution 4:

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
}