Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 594
chatu Avatar asked Dec 05 '25 13:12

chatu


1 Answers

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/

like image 100
Cory Danielson Avatar answered Dec 10 '25 19:12

Cory Danielson