Given I have an array of \"purpose\" objects:
//array of purpose objects:
var purposeObjects = [
{purpose: \"daily\"},
{purpose: \"weekly\"},
{pu
I have created a util service for my angular application. It have two function which use very often.
For example you have object.
First getting value from object recursively without throwing undefined error.
{prop: { nestedProp1: {nestedProp2: somevalue}}}; get nestedProp2 2 without undefined checks.
Second filter array on basis
[{prop: { nestedProp1: {nestedProp2: somevalue1}}}, {prop: { nestedProp1: {nestedProp2: somevalue2}}}];
Find object from array with nestedProp2=somevalue2
app.service('UtilService', function(httpService) {
this.mapStringKeyVal = function(map, field) {
var lastIdentifiedVal = null;
var parentVal = map;
field.split('.').forEach(function(val){
if(parentVal[val]){
lastIdentifiedVal = parentVal[val];
parentVal = parentVal[val];
}
});
return lastIdentifiedVal;
}
this.arrayPropFilter = function(array, field,value) {
var lastIdentifiedVal = null;
var mapStringKeyVal = this.mapStringKeyVal;
array.forEach(function(arrayItem){
var valueFound = mapStringKeyVal(arrayItem,field);
if(!lastIdentifiedVal && valueFound && valueFound==value){
lastIdentifiedVal = arrayItem;
}
});
return lastIdentifiedVal;
}});
For solution for current question. inject UtilService and call,
UtilService.arrayPropFilter(purposeArray,'purpose','daily');
Or more advanced
UtilService.arrayPropFilter(purposeArray,'purpose.nestedProp1.nestedProp2','daily');