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条回答
冷夜・残月
2楼-- · 2018-12-31 04:24

You could use a function like this:

var toObject = function(array) {
    var o = {};
    for (var property in array) {
        if (String(property >>> 0) == property && property >>> 0 != 0xffffffff) {
            o[i] = array[i];
        }
    }
    return o;
};

This one should handle sparse arrays more efficiently.

查看更多
爱死公子算了
3楼-- · 2018-12-31 04:25

As of Lodash 3.0.0 you can use _.toPlainObject

var obj = _.toPlainObject(['a', 'b', 'c']);
console.log(obj);
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>

查看更多
闭嘴吧你
4楼-- · 2018-12-31 04:27

For completeness, ECMAScript 2015(ES6) spreading. Will require either a transpiler(Babel) or an environment running at least ES6.

{ ...['a', 'b', 'c'] }
查看更多
公子世无双
5楼-- · 2018-12-31 04:28

Surprised not to see -

Object.assign({}, your_array)
查看更多
浪荡孟婆
6楼-- · 2018-12-31 04:28

A quick and dirty one:

var obj = {},
  arr = ['a','b','c'],
  l = arr.length; 

while( l && (obj[--l] = arr.pop() ) ){};
查看更多
浪荡孟婆
7楼-- · 2018-12-31 04:28

I would do this simply with Array.of(). Array of has the ability to use it's context as a constructor.

NOTE 2 The of function is an intentionally generic factory method; it does not require that its this value be the Array constructor. Therefore it can be transferred to or inherited by other constructors that may be called with a single numeric argument.

So we may bind Array.of() to a function and generate an array like object.

function dummy(){};
var thingy = Array.of.apply(dummy,[1,2,3,4]);
console.log(thingy);

By utilizing Array.of() one can even do array sub-classing.

查看更多
登录 后发表回答