0

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.

1
  • Also, using Developer Tools you can discover such problems much faster than asking them on StackOverflow. Commented Dec 30, 2012 at 18:18

2 Answers 2

3

Change

for(var i = 0; i <= arr.length; i++) {

to

for (var i = 0; i < arr.length; i++) {

Using <= will go outside the bounds of the array.

jsFiddle Demo

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Now, of course, is works. Have to wait 8 minutes to accept the answer.
0

It is becaouse you should change code to for(var i=0; i < arr.length; i++){: since array length = arr.length, last element index is arr.length - 1, so you just got arr[arr.length] as null object.

1 Comment

The index of the last element is arr.length - 1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.