Reputation: 5101
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);
Upvotes: 2
Views: 5443
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