gpt4 book ai didi

javascript - 使用reduce转换对象的属性值?

转载 作者:行者123 更新时间:2023-11-29 17:41:53 25 4
gpt4 key购买 nike

const ori = {
"AL": "Alabama",
"AK": "Alaska",
"AS": "American Samoa"
}

如何将上面的对象数组连接成

{
"AL": "+ Alabama",
"AK": "+ Alaska",
"AS": "+ American Samoa"
}

使用减少?

我试过了

const r = Object.entries(ori).reduce((accum, [key, value], i) => {
console.log(key)
accum = {[key]: `+ ${value}`}

return accum
},{})
console.log(r)

我只得到了最后一次迭代值。

最佳答案

您只需要使用 ... 运算符将 accum 的当前值与下一个条目组合起来:

const ori = {
"AL": "Alabama",
"AK": "Alaska",
"AS": "American Samoa"
}

const r = Object.entries(ori).reduce((accum, [key, value]) => {
console.log(key)
return {...accum, [key]: `+ ${value}`};
},{})
console.log(r)

关于javascript - 使用reduce转换对象的属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52601737/

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