最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to convert object keys to upper case - Stack Overflow

programmeradmin7浏览0评论

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);

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

Share Improve this question edited Apr 24, 2019 at 9:37 Sohan 6,8396 gold badges40 silver badges58 bronze badges asked Apr 24, 2019 at 9:26 user2024080user2024080 5,10116 gold badges64 silver badges117 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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);

发布评论

评论列表(0)

  1. 暂无评论