如何以这种格式创建对象

时间:2019-03-26 09:44:36

标签: javascript jquery

我正在尝试创建一个对象,该对象以所需的格式在AJAX请求中发送。 在代码中,我能够为每个name元素及其值获取input属性,但是我需要以以下格式创建一个对象。我该如何创建?

{
  "userrole":"",
  "userAttributes":{
    "username":"alks",
    "useraddress":"ajdaa",
    "usercity":"lajsdk"
  }
}
<div class="data-fields-container">
  <div class="input-type" data-attr-name="userrole">
    <input type="text" name="userrole">
  </div>
  <div class="input-type" data-attr-name="username">
    <input type="text" name="username">
  </div>            
  <div class="input-type" data-attr-name="useraddress">
    <input type="text" name="useraddress">
  </div>
  <div class="input-type" data-attr-name="usercity">
    <input type="text" name="usercity">
    </div>
  </div>    
  <button id="submit_data">Submit</button>
$(document).ready(function() {
  $('#submit_data').on('click', function() {
    $('.data-fields-container > .input-type').each(function() {
      dataobj = {};
      var attrkey = $(this).attr('data-attr-name');
      var attrval = $(this).find('input').val();
    })

    $.ajax(function() {
      url: "https://map.net/api/v44",
      data: dataobj,
      type: 'POST',
      dataType: 'Json',
      success: function(data) {
        console.log('successful')
      },
      error: function(request, error) {
        console.log('failed')
      }
    })
  })
})

2 个答案:

答案 0 :(得分:4)

您可以映射serializeArray()结果并像下面那样构造对象:

$(document).ready(function() {
  $('#submit_data').on('click', function() {
    var dataobj = {userrole: $('[name="userrole"]').val()};

    var attr = $('.data-fields-container input:not([name="userrole"])').serializeArray().map(function(o) {
      this[o.name] = o.value;
      return this;
    }.bind({}))[0];

    dataobj['userAttributes'] = attr;

    console.log(dataobj);
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="data-fields-container">
  <div class="input-type" data-attr-name="userrole">
    <input type="text" name="userrole">
  </div>

  <div class="input-type" data-attr-name="username">
    <input type="text" name="username">
  </div>

  <div class="input-type" data-attr-name="useraddress">
    <input type="text" name="useraddress">
  </div>

  <div class="input-type" data-attr-name="usercity">
    <input type="text" name="usercity">
  </div>
</div>

<button id="submit_data">Submit</button>

答案 1 :(得分:0)

dataObj = {
    "userrole":document.querySelector('div.input-type input[name="userrole"]').value,
    "userAttributes":{
        "username":document.querySelector('div.input-type input[name="username"]').value,
        "useraddress":document.querySelector('div.input-type input[name="useraddress"]').value,
        "usercity":document.querySelector('div.input-type input[name="usercity"]').value
    }
}

由于您的JSON格式是静态的,因此您无需遍历输入。