我有一个http.post请求,它发送一个对象作为参数,预期的格式是这样的:
var searchQuery;
var subj;
var body;
var startDate;
var endDate;
{
"search": {
"scope": [2,3,32],
"type": "basic",
"text": {
"value": searchQuery, //string variable coming from UI
"fields": [
subj, body //string variable coming from UI
]
},
"date": {
"type": "range",
"from": startDate, //string variable coming from UI
"to": endDate //string variable coming from UI
}
问题是某些值是可选的意味着如果我不提供searchQuery作为字符串,则应该忽略整个键值,例如“value”:如果我没有提供,则searchqery不应包含在json对象中该变量的值。如果我不提供值,则startDate和endDate也是如此,那么应该从json中忽略date。 那么如何动态地包含或排除来自UI的对象中的密钥对值以及如何在发送到发布请求之前构建该对象?
它应该是这样的吗?
var search = {};
search.text = { value: "", fields: [] };
{value: "", fields: Array(0)}
seach.text.value = "wes";
search.text.value = "wes";
search.text.fields.push("subject");
search.text.fields.push("body");
答案 0 :(得分:1)
您可以创建一个更灵活的功能。
var searchQuery = "";
var subj = null;
var body = "";
var startDate = "";
var endDate = null;
let obj = {
"search": {
"scope": [2, 3, 32],
"type": "basic",
"text": {
"value": searchQuery, //string variable coming from UI
"fields": [
subj, body //string variable coming from UI
]
},
"date": {
"type": "range",
"from": startDate, //string variable coming from UI
"to": endDate //string variable coming from UI
}
}
}
function removeNull(obj) {
return Object.keys(obj).reduce((res, key) => {
if (Array.isArray(obj[key])) {
// If it's an array, filter out the null items
res[key] = obj[key].filter((item) => item != null && item !== "");
} else if (typeof obj[key] === "object" && obj[key] != null) {
// If it's an object, call the function recursively
res[key] = removeNull(obj[key]);
} else if (obj[key] != null && obj[key] !== "") {
// Otherwise, only add it to the results if it's not null
res[key] = obj[key];
}
return res;
}, {});
}
console.log(removeNull(obj));