最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
当前回答
从Lodash 3.0.0开始,你可以使用_.toPlainObject
var obj = _.toPlainObject(['a', 'b', 'c']); 控制台.log(卷); <script src=“https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js”></script>
其他回答
我会使用下划线,但如果没有的话我会使用reduce,初始值为空对象{}
>>> ['a', 'b', 'c'].reduce(function(p, c, i) {p[i] = c; return p}, {})
Object { 0="a", 1="b", 2="c"}
reduce应该在今天的大多数浏览器中广泛使用,参见MDN
下面的方法将数组转换为具有特定给定键的对象。
/**
* Converts array to object
* @param {Array} array
* @param {string} key (optional)
*/
Array.prototype.ArrayToObject = function(key) {
const array = this;
const obj = {};
array.forEach((element, index) => {
if(!key) {
obj[index] = element;
} else if ((element && typeof element == 'object' && element[key])) {
obj[element[key]] = element;
}
});
return obj;
}
前任-
[{名称:“测试”},{名称:test1的}].ArrayToObject(“名字”);
会给
{test: {name: 'test'}, test1: {name: 'test1'}}
并且incase key没有作为参数提供给该方法
i.e. [{name: 'test'}, {name: 'test1'}].ArrayToObject();
会给
{0: {name: 'test'}, 1: {name: 'test1'}}
这不是直接相关的,但我来这里寻找一个合并嵌套对象如一行
const nodes = {
node1: {
interfaces: {if1: {}, if2: {}}
},
node2: {
interfaces: {if3: {}, if4: {}}
},
node3: {
interfaces: {if5: {}, if6: {}}
},
}
解决方案是结合使用reduce和对象扩展:
const allInterfaces = nodes => Object.keys(nodes).reduce((res, key) => ({...res, ...nodes[key].interfaces}), {})
我可能会这样写(因为很少有我手边没有下划线库):
var _ = require('underscore');
var a = [ 'a', 'b', 'c' ];
var obj = _.extend({}, a);
console.log(obj);
// prints { '0': 'a', '1': 'b', '2': 'c' }
为什么没人尝试?在ES6
let arr = ['a','b','c']
let {...obj} = arr
console.log(obj) // {0: 'a', 1: 'b', 2: 'c'}
let {...obj2} = ['a','b','c']
console.log(obj2) // {0: 'a', 1: 'b', 2: 'c'}
很简单的方法吗?