开发者

Set the value of json object dynamically via a function parameter

How could I set the value of an item in a json object by passing in the name of it via a parameter to a function?

eg:

this.loadStates = function() {
    that.setStateIfExists('inStock', true);
}

this.setStateIfExists = function (param, option) {
    // i'd like this to be 'that.selectedFinderOptions.inStock = option'
    that.selectedFinderOptions.param = option;  
}

Is this even possible or 开发者_StackOverflow中文版should I be thinking of doing this differently?


Use an indexer:

that.selectedFinderOptions[param] = option;  


Your use of the phrase "JSON object" has us a bit confused. JSON is a flattened, string representation of the serialization of one or more javascript objects. So, you don't do anything dynamically with a piece of JSON. It's just a string.

If, what you mean is that you have a javascript object instead, then we can discuss options. For a javascript object, you have a couple choices. First off, you can just use an attribute on that object and have it's value reflect what you want:

var myObj = {};
myObj.inStock = true;

Then, anyone can access myObj.inStock and get the current value of that property.

If what, you want is for the value of instock to be computed by a function rather than be static assigned to the object and you want your code to work across all browsers, then you would have to change the way you access that to be via a method call:

var myObj = {};
myObj.getInStockValue = function() {
    // execute whatever code you want here to 
    // compute the desired value and return it when done
};

Then, anyone can access it with myObj.getInStockValue().

In your specific example, you could change this:

this.setStateIfExists = function (param, option) {
    // i'd like this to be 'that.selectedFinderOptions.inStock = option'
    that.selectedFinderOptions.param = option;  
}

to this:

this.setStateIfExists = function (param, option) {
    // i'd like this to be 'that.selectedFinderOptions.inStock = option'
    that.selectedFinderOptions[param] = option;  
}

When the parameter is dynamic and contained in a variable, you use the [param] syntax instead of the .param syntax. They both do the same thing logically, but the [param] syntax is the only one that works when the name of the thing you want to look up is in a variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜