删除JavaScript对象键中的单引号

huangapple go评论53阅读模式
英文:

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(/[&quot;,&#39;]/g, &#39;&#39;));

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月30日 10:17:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76361241.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定