公告
财富商城
积分规则
提问
发文
2018-12-31 03:57发布
皆成旧梦
What is the best way to convert:
['a','b','c']
to:
{ 0: 'a', 1: 'b', 2: 'c' }
you can use spread operator
x = [1,2,3,10] {...x} // {0:1, 1:2, 2:3, 3:10}
If you're using ES6, you can use Object.assign and the spread operator
{ ...['a', 'b', 'c'] }
If you have nested array like
var arr=[[1,2,3,4]] Object.assign(...arr.map(d => ({[d[0]]: d[1]})))
I'd probably write it this way (since very rarely I'll not be having the underscorejs library at hand):
var _ = require('underscore'); var a = [ 'a', 'b', 'c' ]; var obj = _.extend({}, a); console.log(obj); // prints { '0': 'a', '1': 'b', '2': 'c' }
If you are using angularjs you can use angular.extend, the same effect with $.extend of jquery.
var newObj = {}; angular.extend(newObj, ['a','b','c']);
.reduce((o,v,i)=>(o[i]=v,o), {})
[docs]
or more verbose
var trAr2Obj = function (arr) {return arr.reduce((o,v,i)=>(o[i]=v,o), {});}
or
var transposeAr2Obj = arr=>arr.reduce((o,v,i)=>(o[i]=v,o), {})
shortest one with vanilla JS
JSON.stringify([["a", "X"], ["b", "Y"]].reduce((o,v,i)=>{return o[i]=v,o}, {})) => "{"0":["a","X"],"1":["b","Y"]}"
some more complex example
[["a", "X"], ["b", "Y"]].reduce((o,v,i)=>{return o[v[0]]=v.slice(1)[0],o}, {}) => Object {a: "X", b: "Y"}
even shorter (by using function(e) {console.log(e); return e;} === (e)=>(console.log(e),e))
function(e) {console.log(e); return e;}
(e)=>(console.log(e),e)
nodejs > [[1, 2, 3], [3,4,5]].reduce((o,v,i)=>(o[v[0]]=v.slice(1),o), {}) { '1': [ 2, 3 ], '3': [ 4, 5 ] }
[/docs]
ECMAScript 6 introduces the easily polyfillable Object.assign:
Object.assign
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
Object.assign()
Object.assign({}, ['a','b','c']); // {0:"a", 1:"b", 2:"c"}
The own length property of the array is not copied because it isn't enumerable.
length
最多设置5个标签!
you can use spread operator
If you're using ES6, you can use Object.assign and the spread operator
If you have nested array like
I'd probably write it this way (since very rarely I'll not be having the underscorejs library at hand):
If you are using angularjs you can use angular.extend, the same effect with $.extend of jquery.
[docs]
or more verbose
or
shortest one with vanilla JS
some more complex example
even shorter (by using
function(e) {console.log(e); return e;}
===(e)=>(console.log(e),e)
)[/docs]
ECMAScript 6 introduces the easily polyfillable
Object.assign
:The own
length
property of the array is not copied because it isn't enumerable.