首页 > 解决方案 > 使用 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迭代中作曲……我做错了什么?

标签: javascriptarraysecmascript-6

解决方案


你得到了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);


推荐阅读