首页 > 解决方案 > 如何仅将键及其值作为 javascript 对象的参数传递

问题描述

只是为了减少我的代码长度,我决定创建 javascript 函数来初始化 select2 插件。现在我正在编写非常冗长的代码来初始化一个元素。

$("#add_multiple_lr #trips_div .last_added .location_id").select2({
  initSelection: function(element, callback) {
    var elementText = $(element).attr('json-value');
    callback(JSON.parse(elementText));
  },
  minimumInputLength: 2,
  ajax: {
    url: "<?php echo site_url('masters/locations/json_search'); ?>",
    dataType: 'json',
    type: "POST",
    quietMillis: 50,
    data: function (term) {
      return {
        term: term,
        location_type: 'station',
        location_county: ['india', 'bangladesh']
      };
    },
    results: function (data) {
      return {
        results: $.map(data, function (item) {
          return {
            text: item.text,
            id: item.id
          }
        })
      };
    }
  }
});

对于一个或两个元素,编写此代码是可以的,但是当涉及到 10-15 个元素时,我在下面的代码中开发的代码变得非常混乱和冗长。

function initSelect2(reference, url, additional_data = {}, minimumInputLength = 2)
{
  $(reference).select2({
    initSelection: function(element, callback) {
      var elementText = $(element).attr('json-value');
      callback(JSON.parse(elementText));
    },
    minimumInputLength: minimumInputLength,
    ajax: {
      url: url,
      dataType: 'json',
      type: "POST",
      quietMillis: 50,
      data: function (term) {
        return {
          term: term,
          additional_data
        };
      },
      results: function (data) {
        return {
          results: $.map(data, function (item) {
            return {
              text: item.text,
              id: item.id
            }
          })
        };
      }
    }
  });
}

并将其称为

initSelect2(
  "#add_multiple_lr #lr_party, #add_multiple_lr #lr_payable_party",
  "<?php echo site_url('masters/locations/json_search'); ?>",
  {location_type: 'station', location_country: ['india', 'bangladesh']}
);

我只想返回附加数据(参数)的键及其属性。

标签: javascriptjqueryjquery-select2

解决方案


您可以为此使用扩展语法:

return {
    term,
    ...additional_data
};

对于较旧的浏览器,您可以依赖 jQueryextend方法(因为您似乎使用 jQuery):

return $.extend({ term: term }, additional_data);

推荐阅读