公告
财富商城
积分规则
提问
发文
2018-12-31 03:57发布
皆成旧梦
What is the best way to convert:
['a','b','c']
to:
{ 0: 'a', 1: 'b', 2: 'c' }
Quick and dirty #2:
var i = 0 , s = {} , a = ['A', 'B', 'C']; while( a[i] ) { s[i] = a[i++] };
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}), {})
Using ES6 syntax you may do something like:
const arr = ['a', 'b', 'c']; const obj = {...arr}; // -> {0: "a", 1: "b", 2: "c"}
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 {}.
Object.assign()
Array
{}
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.
Here's a solution in coffeescript
arrayToObj = (arr) -> obj = {} for v,i in arr obj[i] = v if v? obj
最多设置5个标签!
Quick and dirty #2:
It's not directly relevant but I came here searching for a one liner for merging nested objects such as
The solution is to use a combination of reduce and object spread:
Using ES6 syntax you may do something like:
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{}
.I ended up using object spread operator, since it is part of the ECMAScript 2015 (ES6) standard.
Made the following fiddle as an example.
Here's a solution in coffeescript