How to use a variable as a key inside object initialiser

前端 未结 2 995
北海茫月
北海茫月 2021-01-14 19:08

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, t

相关标签:
2条回答
  • 2021-01-14 19:44

    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

    0 讨论(0)
  • 2021-01-14 20:00

    Perhaps not quite as elegant but :

    function makeObj (a) {
      if (!(a instanceof Array))
        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

    0 讨论(0)
提交回复
热议问题