0

I have a for loop that searches for a value in an array in my javascript code in couchDb. I want to make it into a function. This should be fairly simple but I am having trouble with it. This is the for loop(Which works perfectly fine):

if (newDoc.destination && newDoc.destination.length > 0) {
    for (var i = 0; i < newDoc.destination.length; i++) {
        if (newDoc.destination[i].address) return;
    }
}
throw({forbidden: 'doc.address is required'});

And this is the way I wrapped it into a function:

function arrayReq(field, message) {
    message = message || "Array must have a " + field;
    if (newDoc.destination && newDoc.destination.length > 0) {
        for (var i = 0; i < newDoc.destination.length; i++) {
            if (newDoc.destination[i].field) return;
        }
    }
    throw({forbidden: message});
}

I would think that the return in the function should stop the function from going any further but it still throws the error. Can someone tell me what I am doing wrong? Btw if i change field into address it works fine. Can I not make the address into a changeable variable?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Anna
  • 13
  • 2
  • 1
    *"I would think that the return in the function should stop the function from going any further but it still throws the error. "* It does. If `newDoc.destination[i].field` is ever truthy, that function will not reach the `throw` at the end. So the problem is elsewhere. – T.J. Crowder Sep 19 '16 at 17:18
  • Note: `throw` is not a function, there's no need to wrap its operand in `()`. It *is* usually best to throw instances of `Error`, though, although you can throw any object you like. – T.J. Crowder Sep 19 '16 at 17:19
  • Should be closed as duplicate of http://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable. –  Sep 19 '16 at 17:45
  • What did you find when you walked through the code with the debugger? I assume you stopped on the second line with the `if` statement, and then examined the value of `newDoc.destination[i].field`, and then what did you find? Did that help you track down the source of the problem? –  Sep 19 '16 at 18:12

1 Answers1

2

I think the problem is that you are trying to use field as both a string variable, and a property of your object inside the destination[] array.

In your code, if the destination[i] object does not have a property called field (not the string value populated in the field parameter, but an actual property named "field") it will never evaluate to true and break out of the function.

To access a property of an object by using the string representation in javascript, you use the indexer syntax.

Try changing it from array.destination[i].field to array.destination[i][field]

Will P.
  • 8,437
  • 3
  • 36
  • 45