javascript - 使用 Array.reduce() 将数组转换为对象
问题描述
我有一个键值对数组:
const arr = [
{ key: 'One', value: '1' },
{ key: 'Two', value: '2' },
{ key: 'Three', value: '3' }
];
我想将上面的数组转换成这种对象:
const obj = {
'One': '1',
'Two': '2',
'Three': '3'
}
通过使用该Array.reduce()
功能。这是我到目前为止所做的:
const obj = arr.reduce( (prev, curr) => prev[curr.key] = curr.value, {} );
这不起作用,因为在该reduce
函数的第二次运行时,prev
未定义,因此我收到此错误:
ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'Two' of undefined
我以为我可以obj
在每次reduce
迭代中作曲……我做错了什么?
解决方案
你得到了undefined
,因为prev
没有 in 中的属性prev[curr.key]
。
这是我的解决方案:
const arr = [
{ key: 'One', value: '1' },
{ key: 'Two', value: '2' },
{ key: 'Three', value: '3' }
];
const result = arr.reduce((prev, curr) => {
return {
...prev,
[curr.key]: curr.value
}
}, {});
console.log(result);
推荐阅读
- r - 从 Excel 工作表中获取 colnames 的响应式应用程序,以供 Shiny 应用程序选择将哪一列放入 ggplot
- java - 在流中打开流
- sql - SQL Server 存储过程插入重复行
- batch-file - 为什么不能传递变量值?
- c - 在链表中以排序方式插入节点
- wordpress - Wordpress 上传 jpg 应该写来自 exif 版权的标题
- java - 从 java 发出 android 系统命令无法正常工作
- javascript - Jquery 关闭事件 - 促销/导航横幅
- windows-installer - 无法卸载使用 MsiEmbeddedChainer 表创建的 MSI
- c# - .NET Framework 如何分配线程 ID?