gpt4 book ai didi

javascript - 使用 reduce 或 map 来大写 JavaScript 对象中的每个属性

转载 作者:行者123 更新时间:2023-11-30 07:12:37 26 4
gpt4 key购买 nike

有没有办法使用 mapreduce 将对象的所有键都大写,以便直接返回结果?

它与 forEach 配合使用效果很好

var o = {
fname: 'john',
lname: 'doe'
}
var result = {}
Object.entries(o)
.forEach((el) => {
result[el[0].toUpperCase()] = el[1]
})


console.log('result', result) // works

但试图改变为

reduce 不工作

var o = {
fname: 'john',
lname: 'doe'
}

var result = Object
.entries(o)
.reduce((accum, curr) => {
return accum[curr[0].toUpperCase()] = curr[1]
}, {})

console.log('result', result)

最佳答案

您需要从回调中返回对象,而不是属性值:

var result = Object.entries(o).reduce((accum, [key, val]) => {
accum[key.toUpperCase()] = val;
return accum;
}, {})

关于javascript - 使用 reduce 或 map 来大写 JavaScript 对象中的每个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48510853/

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