2
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 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.) \$\endgroup\$ – Corey Apr 1 '16 at 15:05
  • \$\begingroup\$ The data has lot of other attributes along with values so it cannot be simplified. \$\endgroup\$ – beeCoder Apr 1 '16 at 16:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.