Goal: Write a function which determines if an array of objects contains an object with a given value for a given field. Return the object if there is such an object and return false otherwise.
The code
var data = [
{isle: 'VF', item: 'Ginger'},
{isle: 'VF', item: 'Spinach'},
{isle: 'Dairy', item: 'Milk'},
{isle: 'Dairy', item: 'Yogurt'}
];
var objwithPropvalueInarr = function(propname, propvalue, arr){
for(var i=0; i <= arr.length; i++){
if (arr[i][propname] === propvalue) {
// console.log('Found object with value ' + propvalue);
return arr[i];
}
};
return false;
};
I entered the above code in Google Chrome console. The following call to the function works:
objwithPropvalueInarr('isle', 'VF', data)
The line above returns data[0] as expected.
However, the following call returns an TypeError (shown after the call)
objwithPropvalueInarr('isle', 'nonexistentpropvalue', data)
TypeError: Cannot read property 'isle' of undefined
arguments: Array[2]
get message: function () { [native code] }
get stack: function () { [native code] }
set message: function () { [native code] }
set stack: function () { [native code] }
type: "non_object_property_load"
__proto__: Error
data[0]['isle'] === 'nonexistentpropvalue' returns false as expected. Should the if condition in the function not return false for every check and then return the false value at the end. Would appreciate if someone can explain the error.
Thank you.