简体   繁体   中英

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?

Example: { 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.

 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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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