chatu
chatu

Reputation: 325

Conditional object in JavaScript for json post

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

Upvotes: 3

Views: 1804

Answers (2)

Cory Danielson
Cory Danielson

Reputation: 14501

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/

Upvotes: 4

Derek
Derek

Reputation: 4751

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;

Upvotes: 0

Related Questions