Sajith
Sajith

Reputation: 2852

How to add Dynamic name to JSON object

I tried following code.

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

and I got the following result

{"empId":true}

But I need to show it like {"5":"true"}. How can I do that?

Upvotes: 0

Views: 83

Answers (2)

Ankit Tyagi
Ankit Tyagi

Reputation: 2375

Use like this :

selected[empId] = true;

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 190907

Try using the indexer operator

selected[empId] = true;

To make true a string, just use a string.

Upvotes: 2

Related Questions