4
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?

Alnitak
  • 334,560
  • 70
  • 407
  • 495
rajaguru r
  • 141
  • 1
  • 3

3 Answers3

3

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

Naeem Shaikh
  • 15,331
  • 6
  • 50
  • 88
-2
//try this
var work = "sample";
var yourJSON = { "publish": { "work": work }};

work = "updated sample";
yourJSON.publish.work = work;
Rahul Nanwani
  • 1,267
  • 1
  • 10
  • 21
-2

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}}
dust
  • 502
  • 6
  • 19