gpt4 book ai didi

javascript - 使用 Array.reduce() 将数组转换为对象

转载 作者:行者123 更新时间:2023-11-28 11:44:56 24 4
gpt4 key购买 nike

我有一个键值对数组:

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迭代...我做错了什么?

最佳答案

您可以在reduce方法中使用Object.assign

const arr = [{ key: 'One', value: '1' },{ key: 'Two', value: '2' },{ key: 'Three', value: '3' }];
const obj = arr.reduce( (prev, {key, value}) => Object.assign(prev, {[key]: value}), {} );
console.log(obj)

关于javascript - 使用 Array.reduce() 将数组转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53130747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com