AlexFF1
AlexFF1

Reputation: 1283

How to create json object dynamically from UI using values from input fields before sending to API

I have a http.post request which sends an object as a parameter, the expected format is like this:

 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
      }

The problem is some values are optional meaning that if I don't provide searchQuery as a string then the whole key value should be ingnored, e.g "value": searchqery should be not included in the json object if I did not provide value to that variable. Same goes for startDate and endDate if I don't provide values then date shouldbe ignored from the json. So how to dynamically include or exlude key pair value in the object that coming from UI and how to build that object before sending to a post request?

Whould it be something like this?

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

Upvotes: 0

Views: 629

Answers (1)

user184994
user184994

Reputation: 18301

You can create a function that's a bit more flexible.

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

Upvotes: 1

Related Questions