如何在不使用循环的情况下将数组转换为 Javascript 中的对象?

lov*_*ate 5 javascript arrays types object

我想转换以下数组:

['a', 'b', 'c']
Run Code Online (Sandbox Code Playgroud)

到以下对象:

{a: 'a', b: 'b', c: 'c'}
Run Code Online (Sandbox Code Playgroud)

我如何在不使用循环的情况下做到这一点,当然?

roo*_*otr 9

你会想要使用这个Array.reduce()方法。

reduce() 方法对数组的每个成员执行一个 reducer 函数(您提供的),从而产生一个输出值。

arr.reduce(callback[, initialValue])
Run Code Online (Sandbox Code Playgroud)

reduce()回调方法需要accumulatorcurrentValue参数。

  • 累加器:在方法的每次迭代中都会记住值,并最终成为最终的返回值。
  • currentValue:正在处理的当前元素array

{}被作为最后一个参数,以提供reduce()作为初始值来下手。并且随着 的每次迭代Array,我们添加到它最终创建最终的Object.

示例:(ES6)

arr.reduce(callback[, initialValue])
Run Code Online (Sandbox Code Playgroud)

示例:(ES5)

const letters = ['a', 'b', 'c'];

const obj = letters.reduce((accumulator, currentValue) => {
  accumulator[currentValue] = currentValue;
  return accumulator;
}, {});

console.log(obj);
Run Code Online (Sandbox Code Playgroud)

参考: Array.prototype.reduce() mozilla 文档。


Nin*_*olz 5

您可以映射对象并使用Object.assign.

var array = ['a', 'b', 'c'],
    object = Object.assign(...array.map(v => ({ [v]: v })));
    
console.log(object);
Run Code Online (Sandbox Code Playgroud)