[英]how to pass only keys and its values as parameter of javascript object
Just to reduce length of my code i decided to create javascript function to initialize select2 plugin. 为了减少代码长度,我决定创建javascript函数来初始化select2插件。 right now i am writing very lengthy code to initilize one element.
现在,我正在编写很长的代码来初始化一个元素。
$("#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
}
})
};
}
}
});
for one or two elements its ok, to write this code, but when it comes to 10-15 elements it becomes really confusing and lengthy code for that i developed below code. 对于一个或两个元素来说,可以编写此代码,但是当涉及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
}
})
};
}
}
});
}
and calling it as 并称其为
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']}
);
i just want to return additional_data (a parameter)'s keys and their property. 我只想返回Additional_data(一个参数)的键及其属性。
You can use the spread syntax for this: 您可以为此使用传播语法:
return {
term,
...additional_data
};
For older browsers you could rely on the jQuery extend
method (as you seem to use jQuery): 对于较旧的浏览器,您可以依赖jQuery
extend
方法(因为您似乎使用jQuery):
return $.extend({ term: term }, additional_data);
When your environment supports latest ECMAScript, you can use object-spread syntax: 当您的环境支持最新的ECMAScript时,可以使用对象扩展语法:
return {
term: term,
...additional_data
};
Otherwise you could use Object.assign(): 否则,您可以使用Object.assign():
return Object.assign({term: term}, additional_data);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.