最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
最好的转换方式是什么:
['a','b','c']
to:
{
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'}
很简单的方法吗?
其他回答
你可以使用累加器,也就是减少。
['a','b','c'].reduce(function(result, item, index, array) {
result[index] = item; //a, b, c
return result;
}, {}) //watch out the empty {}, which is passed as "result"
传递一个空对象{}作为起始点;然后递增地“增大”该对象。 在迭代结束时,结果将是{"0":"a", "1": "b", "2": "c"}
如果数组是键值对对象的集合:
[{ a: 1},{ b: 2},{ c: 3}].reduce(function(result, item) {
var key = Object.keys(item)[0]; //first property: a, b, c
result[key] = item[key];
return result;
}, {});
将产生:{a: 1, b: 2, c: 3}
为了完整起见,reduceRight允许你以相反的顺序遍历数组:
[{ a: 1},{ b: 2},{ c: 3}].reduceRight(/* same implementation as above */)
将产生:{c:3, b:2, a:1}
你的蓄能器可以为你的特定用途的任何类型。例如,为了交换数组中对象的键和值,传递[]:
[{ a: 1},{ b: 2},{ c: 3}].reduce(function(result, item, index) {
var key = Object.keys(item)[0]; //first property: a, b, c
var value = item[key];
var obj = {};
obj[value] = key;
result.push(obj);
return result;
}, []); //an empty array
将产生:[{1:"a"}, {2: "b"}, {3: "c"}]
与map不同,reduce不能用作1-1映射。您可以完全控制要包含或排除的项。因此,reduce可以实现过滤器的功能,这使得reduce非常通用:
[{ a: 1},{ b: 2},{ c: 3}].reduce(function(result, item, index) {
if(index !== 0) { //skip the first item
result.push(item);
}
return result;
}, []); //an empty array
将产生:[{2:"b"}, {3: "c"}]
警告:减少和对象。关键是ECMA第5版的一部分;你应该为不支持它们的浏览器(尤其是IE8)提供一个polyfill。
请参阅Mozilla的默认实现。
初始数组,并将转换为一个对象的键,这将是一个数组的唯一元素,键的值将是具体的键将重复多少次
var jsTechs = ['angular', 'react', 'ember', 'vanilaJS', 'ember', 'angular', 'react', 'ember', 'vanilaJS', 'angular', 'react', 'ember', 'vanilaJS', 'ember', 'angular', 'react', 'ember', 'vanilaJS', 'ember', 'angular', 'react', 'ember', 'vanilaJS', 'ember', 'react', 'react', 'vanilaJS', 'react', 'vanilaJS', 'vanilaJS'] var initialValue = { java : 4 } var reducerFunc = function reducerFunc (initObj, jsLib) { if (!initObj[jsLib]) { initObj[jsLib] = 1 } else { initObj[jsLib] += 1 } return initObj } var finalResult = jsTechs.reduce(reducerFunc, initialValue) console.log(finalResult)
使用javascript lodash库。有一个简单的方法 _。[iteratee = _.identity] mapKeys(对象) 可以进行转换。
你可以使用这样的函数:
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;
};
这个方法可以更有效地处理稀疏数组。
这不是直接相关的,但我来这里寻找一个合并嵌套对象如一行
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}), {})