1

Is there a way to upper-case all keys of an object using map or reduce so the result may be returned directly?

It works fine with 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

But trying to change to

reduce is not working

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)
1252748
  • 14,597
  • 32
  • 109
  • 229

2 Answers2

6

You'll want to return the object from the callback, not the property value:

var result = Object.entries(o).reduce((accum, [key, val]) => {
  accum[key.toUpperCase()] = val;
  return accum;
}, {})
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Is there any way to do this on one line actually? – 1252748 Jan 30 '18 at 15:14
  • `Object.assign(accum, {[key.toUpperCase()]: val})` might do, but I really would not recommend it. If you want simple and readable code, you should prefer a `for … in` loop anyway :-) – Bergi Jan 30 '18 at 15:26
3

You just need to return the accumulator after making the mutation to it, instead of returning on the same line:

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

var result = Object
  .entries(o)
  .reduce((accum, curr) => {
    accum[curr[0].toUpperCase()] = curr[1]
    // Note here: return the accumulator after the mutation:
    return accum
  }, {})

console.log('result', result)
CRice
  • 29,968
  • 4
  • 57
  • 70