var work = 'sample';
{
"publish": {
work: "done"
}
}
Initially the value of work is sample
. If the value of work changes dynamically how can I pass the variable work
into the object?
var work = 'sample';
{
"publish": {
work: "done"
}
}
Initially the value of work is sample
. If the value of work changes dynamically how can I pass the variable work
into the object?
I assume your object to be named obj
,
var obj={
"publish": {}
}
obj.publish[work]= "done";
using square brackets you can define the property using a variable.
So the object will now become
{
"publish": {
"sample": "done"
}
}
var work = 'sample';
var obj = {
"publish": {}
}
obj.publish[work] = "done";
document.write(JSON.stringify(obj))
See this Fiddle
//try this
var work = "sample";
var yourJSON = { "publish": { "work": work }};
work = "updated sample";
yourJSON.publish.work = work;
In your JSON structure, "work" is not in quotation marks. This means the word "work" does not function as a key itself -- only the value of the variable "work" works as a key.
In this respect, either your JSON or your variable declaration above is misleading.
If you meant this:
{ "publish": { "work": "done" } }
Then changing the value of "work" key is as simple as:
myNewStructure = {"publish": {"work": work}}