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.