[英]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);
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: 重新分配变量几乎永远不会独自执行任何操作(即使可以重新分配
key
)-您需要显式地更改现有对象:
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
: 您还可以使用
reduce
,以避免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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.