Skip to content Skip to sidebar Skip to footer

How To Use A Variable As A Key Inside Object Initialiser

In the application I am working, the server pages are used to recieving an input's name as the key for it's value. Is is possible to do this with ajax? In this example, thisName i

Solution 1:

Unfortunately, inside an object initialiser the part on the left side of the : is not treated as a variable but as a string, so the_key is regarded the same as "the_key".

This is the most straightforward way I can think of to add properties with a dynamic name:

var fields = {
    p_session_id: $("[name='p_session_id']").val(),
    p_username: $("[name='p_username']").val()
}
fields[thisName] = thisValue;

Then use fields in your $.ajax call as data: fields

Solution 2:

Perhaps not quite as elegant but :

functionmakeObj (a) {
  if (!(a instanceofArray))
    throw ('Attempt to build object from ' + (typeof a));
  if (a.length % 2)  
    throw ('Attempt to build object from an array length ' + a.length);

  for (var o = {}, i = a.length - 1; i > 0; i -= 2) {
    console.log (a[i-1], a[i]); 
    o[a[i - 1]] = a[i];
  }  
  return o;
}

var thisName = 'Hans PUFAL';
var thisValue = 'Paleoinformaticien';
var session_id = '123edrft456fg';

var o = makeObj (['p_session_id', session_id,
              'p_username', 'HBP',
              thisName, thisValue]);

Available here : http://jsfiddle.net/jstoolsmith/bZtpQ

Post a Comment for "How To Use A Variable As A Key Inside Object Initialiser"