1

I'm not even quite sure what the correct vocabulary is for this, but I have the following code:

$(this).mySpecialMethod({
    propertyOne: "ValueOne",
    propertyTwo: "ValueTwo"
});

I'd like to dynamically control passing in a special propertyThree: "ValueThree" to this depending on other properties on the page/control.

How do I declare an object, add new properties to it based on my requirements and then pass it to the above specified method?

1
  • What you're actually doing here is passing an object (defined using object literal notation) as an argument to the function mySpecialMethod(). Commented Mar 9, 2015 at 16:56

2 Answers 2

4

You can create an object like this:

var myObj = {
    propertyOne: "ValueOne",
    propertyTwo: "ValueTwo"
}

and then add to it as many properties as you want using the right syntax, like this:

if (/* some condition */) {
    myObj.propertyThree = "ValueThree";
}

Now you can pass the object you created to your method:

$(this).mySpecialMethod(myObj);

I suggest you to take a look at the MDN Documentation about Objects in JavaScript: you may find it helpful.

Sign up to request clarification or add additional context in comments.

1 Comment

I will upvote this answer as its more descriptive than mine. ;)
1

Try as follows:

var options = {
    propertyOne: "ValueOne",
    propertyTwo: "ValueTwo"
};

if (conditionIWant === true) {
    options.propertyThree = 'ValueThree';
}

$(this).mySpecialMethod(options);

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.