代码之家  ›  专栏  ›  技术社区  ›  AlexFF1

如何在发送到API之前使用输入字段中的值从UI动态创建json对象

  •  0
  • AlexFF1  · 技术社区  · 8 年前

    我有一个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的对象中动态地包含或排除密钥对值,以及如何在发送到post请求之前构建该对象?

    会是这样的吗?

     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"); 
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   user184994    8 年前

    您可以创建一个更加灵活的函数。

    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));