Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use a variable in JSON.stringify

I use stringify in my node restful server to provide data:

answer = JSON.stringify({activities: result}, null, '\t');
return answer

where result is a js object; i receive the correct output for this:

{
"activities": [
    {
     "id": 1,
     "title": aaa
    },
    { 
     "id": 2,
     "title": bbb
    }
  ]
}

but now i would like to use a variable instead of a fixed string in the left part of stringify function; something like:

var name = "activities";
answer = JSON.stringify({name: result}, null, '\t');

this doesn't work, because name becomes a fixed string in the stringified object

like image 372
Cereal Killer Avatar asked Feb 11 '14 17:02

Cereal Killer


1 Answers

You need to build an object using indexer notation:

var name = ...;
var obj = {};
obj[name] = something;
like image 139
SLaks Avatar answered Oct 08 '22 16:10

SLaks