user2024080
user2024080

Reputation: 5101

How to convert object keys to upper case

I would like to transform lowercase key to uppercase key. But finding my try not works.

what would be the correct approach?

here is my try:

var obj = {
  name: "new name",
  age: 33
}

const x = Object.assign({}, obj);

for (const [key, value] of Object.entries(x)) {
  key = key.toUpperCase();
}


console.log(x);

Live Demo

Upvotes: 2

Views: 5443

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370739

With

key = key.toUpperCase();

Reassigning a variable will almost never do anything on its own (even if key was reassignable) - you need to explicitly to mutate the existing object:

var obj = {
  name: "new name",
  age: 33
}

const x = {};

for (const [key, value] of Object.entries(obj)) {
  x[key.toUpperCase()] = value;
}
console.log(x);

You could also use reduce, to avoid the external mutation of x:

var obj = {
  name: "new name",
  age: 33
}

const x = Object.entries(obj).reduce((a, [key, value]) => {
  a[key.toUpperCase()] = value;
  return a;
}, {});
console.log(x);

Upvotes: 7

Related Questions