我尝试了以下代码。
<script>
var empId = 5;
var selected = {};
selected.empId = true;
console.log(JSON.stringify(selected));
</script>
我得到了以下结果
{"empId":true}
但我需要像 {"5":"true"}
那样显示它。我怎样才能做到这一点?
最佳答案
尝试使用索引器运算符
selected[empId] = true;
要使 true
成为字符串,只需使用字符串即可。
关于javascript - 如何将动态名称添加到 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19953427/