Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am filtering array of objects with object properties provided by the user. The goal is to return an object property 'label' by matching the property 'value'. 'input' provided to the function can be either array of one element or many elements or not an array. I'm using lot of loops to accomplish this. Any suggestions to use less loops will be appreciated.

function filterFunc(input, key, filterData){

  var label = [];
  filterData.forEach(function(fv){
      if(fv.key == key && fv.values) {
          fv.values.forEach(function(v) {
             if(_.isArray(input)){
                 if(input.length > 1 ){
                   input.forEach(function(i){
                      if(v.value == i) {
                        label.push(v.label);
                      }  
                   })
                  }else {
                   if(v.value == input) {
                      label = v.label;
                   }
               }
              } else {
                 if(v.value == input) {
                      label = v.label;
                   }
              }
             }) 
           }
        })
     return label.toString();
  } 



filterData = [{'key':'data1','values':[{'value':'1','label':'one'}]},
               {'key':'data2','values':[{'value':'2','label':'two'}]}]

Note: Values are not always present. Input to the function is key and value. The function to should return the label for the input value.

share|improve this question
    
Do you have control over the data model? The more appropriate way to do this is: filterData = { data1: [{ value: '1', label: 'one' }], data2: [{ value: '2', label: 'two' }] }; Then your logic becomes simpler. (I'm assuming the inner arrays are necessary, but it becomes even simpler if you can take those out too.) – Corey Apr 1 at 15:05
    
The data has lot of other attributes along with values so it cannot be simplified. – Anu Apr 1 at 16:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.