Javascript 将javascript数组转换为具有相同键/值的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38536974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:34:46  来源:igfitidea点击:

Convert javascript array to object of same keys/values

javascriptjqueryarrayssweetalert

提问by Phiter

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

我有一个返回数组的函数,如下所示:

enter image description here

在此处输入图片说明

But I'm trying to populate a SweetAlert2 dialog.

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

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:

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

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

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

回答by Amit

This can be done with a simple reducecall:

这可以通过一个简单的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));

回答by user3163495

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

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

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

回答by Cem Arguvanl?

if you are using jQuery;

如果您使用的是 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'}];

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

回答by onlyurei

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.

没有常见的 ESlint 规则错误。