简体   繁体   English

如何更改对象属性以使其具有双引号?

[英]How do i change object properties to have double quotes?

How do I change an object to have double quotes as a property in JavaScript? 如何在JavaScript中将对象更改为具有双引号作为属性?

Example: { C: 10, H: 16, N: 5, O: 13, P: 3 }​​​​ => ​​​​​​​​​​{ "C": 10, "H": 16, "N": 5, "O": 13, "P": 3 } 范例:{C:10,H:16,N:5,O:13,P:3} = = {“ C”:10,“ H”: 16,“ N”:5,“ O”:13,“ P”:3}

You can stringify it. 您可以将其字符串化。

 var obj = { C: 10, H: 16, N: 5, O: 13, P: 3 }, json = JSON.parse(JSON.stringify(obj)); console.log(json); 

I think this is what Niputi expected: double quotes as a property. 我认为这就是Niputi的期望:双引号作为一种财产。

 let input = {C: 10, H: 16, N: 5, O: 13, P: 3}; let output = {}; for (let key in input) { output['"' + key + '"'] = input[key]; } console.log(output); 

Note, the original object's properties remain unchanged in the preceding two solutions in which each creates a new object. 请注意,在前两个解决方案中,原始对象的属性保持不变,在每个解决方案中,每个解决方案都创建一个新对象。 The OP indicated a desire to alter the original object. OP表示希望更改原始对象。 In that case, either of the preceding solutions is fine in conjunction with deleting the unquoted properties, too. 在那种情况下,结合删除未引用的属性,上述任一解决方案都可以。 One way to accomplish this feat in JavaScript is as follows: 在JavaScript中实现此功能的一种方法如下:

var o = {
   C: 10,
   H: 16,
   N: 5,
   O: 13,
   P: 3
};

for (let k in o) {
   o["\"" + k + "\""] = o[k];
   delete o[k];
 }

 // the changed object
 for (let p in o) {
   console.log(p, o[p]);
 }

See live code 查看实时代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM