英文:
Remove single quotes from Javascript object keys
问题
我正在尝试让对象的键不被单引号包围。
let arr = [2, 3, 4, 11];
let myObj = {};
myObj[arr[2]] = true;
console.log(myObj);
上述代码输出结果为 { '4': true }
我如何去掉数字 4 周围的单引号,使其显示为 { 4: true }?
英文:
I'm trying to have the key of the object not be surrounded by single quotes.
let arr= [2, 3, 4, 11];
let myObj={};
myObj[arr[2]]=true;
console.log(myObj);
The above code outputs the result { '4': true }
How do I remove the single quotes around 4 and have it display as { 4: true }
答案1
得分: 1
你可以这样做:
const arr = [2, 3, 4, 11];
const myObj = {};
myObj[arr[2]] = true;
const str = JSON.stringify(myObj);
console.log(str.replace(/[",']/g, ''));
英文:
You can do it like so:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const arr = [2, 3, 4, 11];
const myObj = {};
myObj[arr[2]] = true;
const str = JSON.stringify(myObj);
console.log(str.replace(/[",']/g, ''));
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论