我正在使用jQuery的$.param()
来按以下格式序列化对象:
var queryParams = {
firstNm: null,
lastNm: 'M',
id: null,
email: null
}
当我使用$.param(queryParams)
时,我会得到以下内容:
firstNm =安培; lastNm = M和ID =安培;电子邮件=
我想要的只是:
lastNm = M
我希望任何null或空的参数都不会显示在输出中。这可能是使用jQuery的$.param()
,还是需要自定义序列化?
修改
这不是this question的副本。该问题更多地涉及MediaWiki API,并且当参数为null或为空时不包括=
,并且仅包括键值对的键。我的问题是,如果值为null或为空,是否可以完全从输出中取消键值对。
答案 0 :(得分:5)
您可以编写自己的函数来排除空值和空值:
var queryParams = {
firstNm: null,
lastNm: 'M',
id: null,
email: null
}
function isEmpty(value){
return value == null || value == "";
}
for(key in queryParams)
if(isEmpty(queryParams[key]))
delete queryParams[key];
// queryParams now = { lastNm: "M"}
如果您从表单中获取此值,则可以执行以下操作:
$("#form :input[value!='']").serialize()
答案 1 :(得分:1)
另一种实现删除序列化字符串中空参数的方法。
/****** REMOVE DUPLICATES ******/
WITH CTE AS(
SELECT *,
RN = ROW_NUMBER()OVER(PARTITION BY OrderId ORDER BY OrderId)
FROM [dbo].[Order Details]
)
DELETE FROM CTE WHERE RN > 1
/****** Script for merging after removing duplicates from destination table ******/
BEGIN
WITH dedupe AS (SELECT DISTINCT OrderID,ProductID,UnitPrice,Quantity,Discount
from[dbo].[Order Detai11])
MERGE [dbo].[Order Details]
USING dedupe AS tblMergeDetail
ON ( tblMergeDetail.OrderId = [dbo].[Order Details].OrderId )
WHEN MATCHED THEN
SET ProductID = tblMergeDetail.ProductID,
UnitPrice = tblMergeDetail.UnitPrice,
Quantity = tblMergeDetail.Quantity,
Discount = tblMergeDetail.Discount
WHEN NOT MATCHED THEN
INSERT (OrderID,ProductID,UnitPrice,Quantity,Discount)
VALUES (
tblMergeDetail.OrderID,
tblMergeDetail.ProductID,
tblMergeDetail.UnitPrice,
tblMergeDetail.Quantity,
tblMergeDetail.Discount
);
答案 2 :(得分:0)
您可以在此处排除空值,并将您的属性保留在对象中: https://jsfiddle.net/leojavier/bxc57o3v/2/
var queryParams = {
firstNm: null,
lastNm: 'M',
id: null,
email: null
}
var query = {}
for(item in queryParams) {
if(queryParams[item] != null && queryParams[item].length > 0) {
query[item] = queryParams[item]
console.log(query)
console.log($.param(query));
}
}