3

I have a function named update that takes some options and post to my php using $.post:

 function update(options){
   $.post('update.php',{update: options}, function(data, textStatus, jqXHR){
     // debug stuff from php
   });
 }

I call my function as follows:

 update({'id': id, 'option': val});

What I would like to know is how I can make a conditional inside the options? For example:

 var option = $(this).attr('class') == 'check' ? 'check' : 'ok'; // assuming option is ok

 update({'id': id, 'ok': val}); // instead of option

 update({'id': id, option: val}); // i want to have the conditional

2 Answers 2

4

You can access Javascript objects in the same way that you access arrays. This syntax supports dynamic property names/keys.

options[variable] = 'value';

Example:

var x = 'customProperty'
,   y = {}
;

y.x = 12; //y.x = 12
y[x] = 11; //y.customProperty = 11... same as y['customProperty'] = 11

http://jsfiddle.net/CoryDanielson/Dugdd/

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

1 Comment

He wants option be a dynamic key I think
0

Essentially you set your object as such:

var x = {};

Then assign the exact property you want

var prop_name = $(this).attr('class') == 'check' ? 'check' : 'ok';
x[prop_name] = YOUR_VALUE;

1 Comment

If you're asking to put the actual condition itself inside the JSON string, the answer is "no" you can't do that because the condition expression will be evaluated into its boolean result (true or false) and will always return the value specified by each part of your ternary statement.

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.