将对象值附加到 javascript 中的字符串

Appending object values to string in javascript

我有一个对象数组如下:

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

我想要实现的是,this.filterConditionString 的值应该如下所示:

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

注意事项:-

  1. 如果 filter.value 不是数组,则 filter[filterQueryParamName] 应该用 && 分隔。

例如:- entityLeveId == 909 && entityTypeId == 910

  1. 如果 filter.value 是一个数组,那么只有相同 filter[filterQueryParamName] 的不同值应该用 || 分隔, filter[filterQueryParamName] 的其他值应该用 [=15 分隔=].

例如:- && ( filter2 ==112 || filter2 == 113 ) &&

如果还有什么不清楚的地方,请告诉我。

正如评论中Eknot 已经提到的,您的代码可读性不是很好。我无法理解您的代码,因为它太复杂了。你写下了自己的步骤,为什么不照着做呢!

我给你写了一个更易读的例子来说明如何做到这一点。如果您浏览代码,您会发现我或多或少地执行了您在问题中描述的步骤:


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(' && ')

}

我测试了它,它适用于你给定的数据。

我想问你,你用这个做什么? .

分解为步骤

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
  }
];

function createFilterConditions(filterConditionList) {
  const s = filterConditionList.map(li => {

    // get the key name
    const key = li.filterQueryParamName

    // build the filter portion of string
    if(Array.isArray(li.value)) {
      // step 1: add filter == value 
      let si = li.value.map(vi => `${key} == ${vi}`)
      
      // step 2: join with '||'
      si = si.join(' || ')

      // step 3: wrap in parenthesis
      return `(${si})`

    } else {
      return key + ' == ' + li.value 
    }

  })

  // join each list element with &&
  return s.join(' && ')
}

或者您可以链接字符串方法以使其更简洁

// concise version
function createFilterConditionsConcise(filterConditionsList) {
  return filterConditionsList.map(li => {
    return Array.isArray(li.value) 
      ? `(` + li.value.map(vi => `${li.filterQueryParamName} == ${vi}`).join(' || ') + ')'
      :li.filterQueryParamName + ' == ' + li.value  

  }).join(' && ')

}