Given I have an array of \"purpose\" objects:
//array of purpose objects:
var purposeObjects = [
{purpose: \"daily\"},
{purpose: \"weekly\"},
{pu
The error was that you cannot use this
in the grep, but you must use a reference to the element. This works:
function findPurpose(purposeName){
return $.grep(purposeObjects, function(n, i){
return n.purpose == purposeName;
});
};
findPurpose("daily");
returns:
[Object { purpose="daily"}]
Best, Fastest way is
function arrayLookup(array, prop, val) {
for (var i = 0, len = array.length; i < len; i++) {
if (array[i].hasOwnProperty(prop) && array[i][prop] === val) {
return array[i];
}
}
return null;
}
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');
I personally use a more generic function that works for any property of any array:
function lookup(array, prop, value) {
for (var i = 0, len = array.length; i < len; i++)
if (array[i] && array[i][prop] === value) return array[i];
}
You just call it like this:
lookup(purposeObjects, "purpose", "daily");
One more solution:
function firstOrNull(array, expr) {
for (var i = 0; i < array.length; i++) {
if (expr(array[i]))
return array[i];
}
return null;
}
Using: firstOrNull([{ a: 1, b: 2 }, { a: 3, b: 3 }], function(item) { return item.a === 3; });
This function don't executes for each element from the array (it's valuable for large arrays)