我想转换以下数组:
['a', 'b', 'c']
到以下对象:
{a: 'a', b: 'b', c: 'c'}
我该如何在不使用循环的情况下做到这一点?
您将要使用该Array.reduce()
方法。
reduce()方法在数组的每个成员上执行reducer函数(由您提供),从而产生单个输出值。
arr.reduce(callback[, initialValue])
该reduce()
回调方法需要accumulator
和currentValue
参数。
array
。将{}
被作为最后一个参数,以提供reduce()
作为初始值来下手。并且随着的每次迭代Array
,我们都会添加到最终创建最终版本Object
。
示例:(ES6)
const letters = ['a', 'b', 'c'];
const obj = letters.reduce((accumulator, currentValue) => {
accumulator[currentValue] = currentValue;
return accumulator;
}, {});
console.log(obj);
示例:(ES5)
var letters = ['a', 'b', 'c'];
var obj = letters.reduce(function (accumulator, currentValue) {
accumulator[currentValue] = currentValue;
return accumulator;
}, {});
console.log(obj);
参考: Array.prototype.reduce() mozilla文档。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句