简体   繁体   English

在Javascript中将数组转换为对象

[英]Converting an Array into object in Javascript

I want to know the best way to convert an array in Js to object. 我想知道将Js中的数组转换为对象的最佳方法。

This is the sample of what i want to do. 这是我想要做的样本。 Input => ['abc', 'def']; 输入=> ['abc','def']; Output => { abc: true, def: true } 输出=> {abc:true,def:true}

I have done it using the code below. 我使用下面的代码完成了它。 But just wanted to know if 但只是想知道是否

**function toObject(strings) {
    var rv = {}
    strings.forEach(string => {
        rv[string] = true
    })
  return rv
}**

This function serves the purpose. 此功能用于此目的。 But any experts out there with a best and efficient way possible. 但任何专家都能以最好,最有效的方式开展工作。

Not sure what you mean by best and efficient way possible , since yours is alright according to me, this is a less versbose version 不知道你的意思是什么,以最好和最有效的方式 ,因为根据我的不错 ,这是一个不那么精简的版本

var output = strings.reduce( (a,c) => (a[c]=true, a), {})

Demo 演示

 var strings = ['abc', 'def']; var output = strings.reduce( (a,c) => (a[c]=true, a), {}); console.log(output); 

You could map single objects and assign it to the same object. 您可以映射单个对象并将其分配给同一对象。

 var array = ['abc', 'def'], object = Object.assign(...array.map(key => ({ [key]: true }))); console.log(object); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM