11

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

3 Answers 3

15

You need to build an object using indexer notation:

var name = ...;
var obj = {};
obj[name] = something;
Sign up to request clarification or add additional context in comments.

2 Comments

With ES6, you can do it inside the object literal assignment, like { [name]: something }
write the answer in syntax of the question for the user readability.
6

If you want JSON.stringify() Object then try this:

var field = "my_field_name";

var obj = {};

obj[field] = value;

var myJSON = JSON.stringify(obj);

Comments

3

You can use new with an anonymous function to do it as well:

answer = JSON.stringify(new function(){ this[name] = result; }, null, '\t');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.