0

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 should I be thinking of doing this differently?

1
  • If you have JSON you would need to deserialise it, set the property on the resulting object, and then turn it back into JSON. (Unless you plan to do it all as string manipulation.) Do you really mean "object" rather than "JSON object"? Commented Aug 24, 2011 at 23:48

2 Answers 2

2

Use an indexer:

that.selectedFinderOptions[param] = option;  
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.