0

I have the weirdest problem with my code and I don't know how to solve it. I have an array of objects which I would like to loop through and match the variable dossiernummer to the selected dossiernummer to extract the zipcode of the object. This is all a bit too much for one question and I am certain I can code this, but my array seems empty whenever I add a loop!

My code:

  $('select[name=company]').on('change', function() {
  // The selected `dossiernummer`
  console.log($(this).val());
  // The array of `Objects` 
  console.log(results);
  geocodeAddress(geocoder, map, address);
  });

When using the Chrome console, I can see the filled array of objects, so I am 100% sure that the data is there! I also checked the variables, and it all matches:

enter image description here

But! Now I would like to loop through the array of objects:

$('select[name=company]').on('change', function() {
for (var j = 0; j < results.length; j++){
    if (results[j]['dossiernummer'] == $(this).val()){
       var address = results[j]['postcode']
    }
}
geocodeAddress(geocoder, map, address);
});

This gives the following error in my console: enter image description here

I am not advanced with JavaScript, so this error is probably very silly but I can't figure it out. Help is much appriciated!

Edit:

The data is coming from an API to fill a Select2

params.page = params.page || 1;

                        var results = [];

                        if(data.totalItemCount > 0){
                            $.each(data._embedded.rechtspersoon, function(i, v) {
                                v.id = v.dossiernummer ;

//                                console.log(v);

                                if(v.actief == 1){
                                    results.push(v);
                                }
                            });
                            // the code function which i described ->
                            KvkGoogleMaps(results);
                        }
                        return {
                            results: results,
                            pagination: {
                                more: (params.page * 30) < data.totalItemCount
                            }
                        };
Anna Jeanine
  • 3,975
  • 10
  • 40
  • 74
  • 1
    Include the code where `results` is defined/modified/etc. – Seth Flowers Mar 23 '17 at 18:11
  • Seems strange if all other/surrounding code is equivalent. What/how is `results` set? Are you saying that placing a `console.log(results)` above your `for` loop in the second example will also produce the same array output as indicated in the first example? – barry-johnson Mar 23 '17 at 18:11
  • I adjusted my question! Thank you – Anna Jeanine Mar 23 '17 at 18:18
  • Sounds like a duplicate of [Is Chrome's JavaScript console lazy about evaluating arrays?](http://stackoverflow.com/q/4057440/1048572) - wait for the array to get filled before you iterate it – Bergi Mar 23 '17 at 18:22
  • Still hard to see why/how `results` exists in the first place because the two snippets aren't in context. What happens if you `console.log(results);` right before the loop in the second example? – Will Mar 23 '17 at 18:24
  • I am seeing what is going wrong! When the `.on('change.....'`, the console.log(results) is printed twice but once empty and once filled with data! I am sorry that this is such a random question. The results is filled and defined in the extra code which I have provided. – Anna Jeanine Mar 23 '17 at 18:26
  • I have updated the screenshot in the question. – Anna Jeanine Mar 23 '17 at 18:28
  • 1
    It looks like you should be referencing `results.results` to get the array, unless you are saying it is unwrapped somewhere else. Also, it is unclear from this code that `results` would be in scope (it may well be, it's just not clear from what is presented). – barry-johnson Mar 23 '17 at 18:35
  • 1
    BTW - based on your updated screenshot and mention of it printing once as undefined and once with data, I assume your problem is one of asynchronous operation such that in the first pass you haven't yet populated the results. Possibly this change handler is getting fired before you expect it to. – barry-johnson Mar 23 '17 at 18:38
  • Hmm oke. I am sorry I can't explain the problem which I am having better.. The on.change is executed two times for some reason which I do not understand.. – Anna Jeanine Mar 23 '17 at 18:41
  • Anna - consider throwing a `debugger` statement at the top of the `change` event handler so you can look at when it is being triggered. Otherwise, the "duct tape"/quick hack solution would be to just put a guard on your change handler to bail if `results` is undefined. e.g. `if (results===undefined) return;` as the first line of the handler. – barry-johnson Mar 23 '17 at 18:49
  • Thank you for trying your best to help me out! I am gonna start a die hard debugger session. I'll get back to this if I find a solution! – Anna Jeanine Mar 23 '17 at 19:00
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/138865/discussion-between-barry-johnson-and-anna-jeanine). – barry-johnson Mar 23 '17 at 19:00

1 Answers1

-1

The problem is your results array is undefined. I cannot tell you exactly how to fix this, since you've only given us a snippet without context.

This problem of yours seems to be due to the fact that JavaScript has lexical scope, something similar to dynamic scope. If you call a function, the scope in that function is different than the scope in the parent from which it was called from. Therefore, it could be possible that scope from the called function (the anonymous one in your example) cannot access the results array from the parent.

It would be helpful if you posted more of your code in order to be able to tell you the exact problem.

More about JavaScript lexical scope.

Community
  • 1
  • 1
leonz
  • 1,107
  • 2
  • 10
  • 32