Convert Array to Object

2018-12-31 03:57发布

What is the best way to convert:

['a','b','c']

to:

{
  0: 'a',
  1: 'b',
  2: 'c'
}

30条回答
泛滥B
2楼-- · 2018-12-31 04:34

Quick and dirty #2:

var i = 0
  , s = {}
  , a = ['A', 'B', 'C'];

while( a[i] ) { s[i] = a[i++] };
查看更多
浅入江南
3楼-- · 2018-12-31 04:36

It's not directly relevant but I came here searching for a one liner for merging nested objects such as

const nodes = {
    node1: {
        interfaces: {if1: {}, if2: {}}
    },
    node2: {
        interfaces: {if3: {}, if4: {}}
    },
    node3: {
        interfaces: {if5: {}, if6: {}}
    },
}

The solution is to use a combination of reduce and object spread:

const allInterfaces = nodes => Object.keys(nodes).reduce((res, key) => ({...res, ...nodes[key].interfaces}), {})
查看更多
不流泪的眼
4楼-- · 2018-12-31 04:38

Using ES6 syntax you may do something like:

const arr = ['a', 'b', 'c'];
const obj = {...arr}; // -> {0: "a", 1: "b", 2: "c"} 

查看更多
怪性笑人.
5楼-- · 2018-12-31 04:39
Object.assign({}, ['one', 'two']); // {0: 'one', 1: 'two'}

Easy way in modern JavaScript is to use Object.assign() that does nothing but copying key:value from one object to another. In our case, Array donates properties to new {}.

查看更多
与风俱净
6楼-- · 2018-12-31 04:41

I ended up using object spread operator, since it is part of the ECMAScript 2015 (ES6) standard.

const array = ['a', 'b', 'c'];
console.log({...array});
// it outputs {0:'a', 1:'b', 2:'c'}

Made the following fiddle as an example.

查看更多
浪荡孟婆
7楼-- · 2018-12-31 04:41

Here's a solution in coffeescript

arrayToObj = (arr) ->
  obj = {}
  for v,i in arr
    obj[i] = v if v?
  obj
查看更多
登录 后发表回答