将 javascript 数组转换为相同 keys/values 的对象

Convert javascript array to object of same keys/values

我有一个函数,returns一个数组,如下:

但我正在尝试填充 SweetAlert2 对话框。

As the documentation exemplifies,所需的输入如下所示

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

考虑到键与值相同,我如何将我的数组转换为所需的格式?

所以,结果是这样的:

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

我试过JSON.stringify,但输出不是我需要的:

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

关键是您可以使用 obj["string"] 技术分配属性:

function ArrayToObject(arr){
    var obj = {};
    for (var i = 0;i < arr.length;i++){
        obj[arr[i]] = arr[i];
    }
    return obj
}

这可以通过简单的 reduce 调用来完成:

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

如果您正在使用 jQuery;

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

如果你没有;

Object.assign({}, my_array);

另一个例子;

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

Object.assign(
  {},
  ...['value1', 'value2', 'value3', 'value4', 'value5'].map((value) => ({
    [value]: value,
  })),
)

returns

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

没有常见的 ESlint 规则错误。