Search code examples
javascriptstring-concatenation

Appending object values to string in javascript


I have an array of object as below :

var filterConditionString = "";
var filterConditionsList = [
  {
    apiDataProperty: "LevelId",
    filterQueryParamName: "entityLevelId",
    value: 909
  },
  {
    apiDataProperty: "TypeId",
    filterQueryParamName: "entityTypeId",
    value: 910
  },
  {
    apiDataProperty: "WORKFORCE",
    filterQueryParamName: "filter1",
    value: 11
  },
  {
    apiDataProperty: "MAIN_INSTRUMENT",
    filterQueryParamName: "filter2",
    value: [112, 113]
  },
  {
    apiDataProperty: "MATRIX_ENTITY",
    filterQueryParamName: "filter3",
    value: [1131, 213, 413]
  },
  {
    apiDataProperty: "VERSIONID",
    filterQueryParamName: "filter4",
    value: 1141
  }
];

createFilterConditions(this.filterConditionsList);
console.log(this.filterConditionString);

function createFilterConditions(filterList) {
  this.filterConditionString = "";
  let separator = "",
    prevFilter = "",
    prevArrayFilter = "";
  filterList.map((filter) => {
    if (Array.isArray(filter.value)) separator = "||";
    else separator = "&&";

    if (filter.value) {
      if (Array.isArray(filter.value)) {
        filter.value.forEach((arrVal) => {
          this.filterConditionString =
            prevArrayFilter +
            `${filter.filterQueryParamName} == ${filter.value} ${separator}`;
          prevArrayFilter = this.filterConditionString;
        });
        if (this.filterConditionString.substr(this.filterConditionString.length - 2) == "||") this.filterConditionString = this.filterConditionString.substr(0,this.filterConditionString - 2 );
        this.filterConditionString = prevFilter + "(" + this.filterConditionString + ") &&"
        prevArrayFilter = this.filterConditionString;
        prevFilter = this.filterConditon;
      } else {
        this.filterConditionString = this.filterConditionString? prevFilter +`${filter.filterQueryParamName} == ${filter.value} ${separator}`: `${filter.filterQueryParamName} == ${filter.value} ${separator}`;
        prevFilter = this.filterConditionString;
        prevArrayFilter = this.filterConditionString;
      }
    }
    return this.filterConditionString;
  });
}

What I am trying to achieve is, the value of this.filterConditionString value should as below :

entityLeveId == 909 && entityTypeId == 910 && filter1 == 11 && ( filter2 ==112 || filter2 == 113 ) && ( filter3 ==1131 || filter3 == 213|| filter3 ==413 ) && filter4 == 1141

Points to be taken care of :-

  1. if filter.value is not an array then filter[filterQueryParamName] should be separated by &&.

for eg :- entityLeveId == 909 && entityTypeId == 910

  1. if filter.value is an array then only different values of same filter[filterQueryParamName] should be separated by || and other values of filter[filterQueryParamName] should be separated by &&.

for eg:- && ( filter2 ==112 || filter2 == 113 ) &&

let me know if anything is still unclear.


Solution

  • As Eknot already mentioned in a comment, your code is not very readable. I was not able to understand your code since it's way too complicated. You wrote your own steps down, why not follow them!

    I wrote u a more readable example on how to do this. If you go through the code, you can see I did more or less the steps you described in your question:

    
    function createFilterConditions(filterList) {
    
        // store all filters in an array
        const filters = []
        
        // helper for building up == chain.
        // keep it in one place!
        function condition(name, value) {
            return `${name} == ${value}`
        }
    
        // iterate the list!.
        for(let filter of filterList) {
            // read out used data.
            const name = filter['filterQueryParamName']
            const values = filter['value']
    
            // Step 1, if filter is NOT an array!
            // First to the simple values.
            // NO array?  Then store the condition!.
            if(Array.isArray(values) === false) {
                filters.push(condition(name, values))
            }
    
            // Step 2: If values is an array
            // Performance wise, it's probably not a big deal to check it twice. Generally prefer readability over performance.
            // Build up a condition Group joined with '||' separator and wrapped in parenthesis. 
            
            else if(Array.isArray(values)) {
                
                const sub_filters = []
    
                // add each sub value in the array!.
                for(let value of values) {
                    sub_filters.push(condition(name, value))
                }
    
                // join the arguments together and wrap em in 
                // OR Operator ('||')
                const sub_condition = `(${sub_filters.join(' || ')})`
    
                // add the filter to filters array.
                filters.push(sub_condition)
            }
        }
    
        // Now, that all filters have been evaluated and normalised
        // it's needed to join ur whole group with ' && ' operator (and the space ofc..)
        // this is like step 3. In step 2 you are doing multiple things. 
        return filters.join(' && ')
    
    }
    

    I tested it and it works with your given data.

    What i want to know from you, what do you use this for? .