简体   繁体   中英

node,js add an outer level to json using a variable as key name

I have a standard JSON stored in a variable and am able to add a top level key when directly using text but a variable,

[{"myKey":"my value"}]

is stored in orginalJson . I then add a top level key as text

var newJson = JSON.parse(orginalJson);
newJson = { myText: newJson };

gives

{ "myText": [{"myKey":"my value"}]}

I would now like to replace the text in the code with a variable

var newVar = "newtext";    
var newJson = JSON.parse(orginalJson);
newJson = { newVar: newJson };

however I do not get the var value as expected, just the name of var not the value

expecting

{ "newtext": [{"myKey":"my value"}]}

but get

{ "newVar ": [{"myKey":"my value"}]}

what is the correct way to use a var in this instance. I have read other posts suggesting using a push but I have not had any luck understanding the correct syntax.

The correct way of using var is;

var newVar = "newText"
var newJson = {}
newJson[newVar] = JSON.parse(originalJson)

This will give you

{ "newVar ": [{"myKey":"my value"}]}

You have to first create the object, then use bracket notation for the key
Because you're using the same variable to hold the newly modified value, we'll need a temporary object.
The better option would probably be to not use the same variabel twice

 var orginalJson = '{"test":"test"}'; var newVar = "newtext"; var newJson = JSON.parse(orginalJson); var tempObj = {}; tempObj[newVar] = newJson; newJson = tempObj; console.log(newJson) 

Or in ES2015 you can use dynamic keys

 var orginalJson = '{"test":"test"}'; var newVar = "newtext"; var newJson = JSON.parse(orginalJson); newJson = { [newVar]: newJson }; console.log(newJson); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM