如何将动态名称添加到JSON对象

时间:2013-11-13 12:09:27

标签: javascript arrays json dynamic

我尝试了以下代码。

<script>
var empId = 5;
var selected = {};
selected.empId = true;
console.log(JSON.stringify(selected));
</script>

我得到了以下结果

{"empId":true}

但我需要像{"5":"true"}一样展示它。我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

尝试使用索引器运算符

selected[empId] = true;

要使true成为字符串,只需使用字符串。

答案 1 :(得分:0)

像这样使用:

selected[empId] = true;
相关问题