如何使用 reduce 将数组转换为对象?

How to use reduce to transform an array into an object?

多亏了另一个 SO 线程,多亏了 reduce(),我才设法将一个数组的数组转换为一个对象。但是,我不明白为什么会这样。

有人可以向我解释为什么我不能只写 => acc[key] = value, {} 吗?这种语法对我来说很有意义。但是它returns21!仅当我在我的对象分配和我的起始值 {} 之间添加 ,acc 时它才有效。此外,ESLint 声称它是一个 unexpected use of comma operator

const myArray = [["player1", 30], ["player2", 21]];
const obj = myArray.reduce((acc, [key, value]) => (acc[key] = value, acc), {});

console.log("obj : ", obj);

这个我也写过。它也很好用,但我仍然想知道为什么第一个脚本有效:

const myArray = [["player1", 30], ["player2", 21]];
const obj = myArray.reduce((acc, [key, value]) => Object.assign(acc, {[key]: value}),{});

console.log("obj : ", obj);

当您使用 reduce() 时,您需要 return 来自回调的累加器 acc

您需要了解的第二件事是隐含的 return。当您使用没有 {}return 的箭头函数 => 时,=> 之后的值成为函数的 return 值。

您需要了解的另一件事是逗号运算符。当您在两个或多个表达式之间使用逗号运算符时,它的计算结果为最后一个。

console.log(("first", "second", "third"))

在上面的代码片段中,整个表达式 ("first", "second", "third") 的计算结果为 "third"

你的情况也是如此 (acc[key] = value, acc) 计算结果为 acc

const myArray = [["player1", 30], ["player2", 21]]
const toObj = myArray.reduce((acc, [key, value]) => {
  acc[key] = value;
  return acc;
})
console.log(toObj)

Could someone please explain to me why I can't only write => acc[key] = value, {} ?

我在上面提到,当你使用 reduce() 时,你需要从你的函数中 return acc。因此,您可以使用上述方式 acc[key] = value 从每次迭代中获取 returned。并且 acc[key] = value 将始终评估为 value 因此整个 reduce 方法 returns 最后一个 value21