0

really strange one this.

I'm calling an AJAX call which returns an array of items using JSON (should be 5).

In the success function I console.log the response which shows me the array which has 5 items.

(5) [{…}, {…}, {…}, {…}, {…}]
    0: {id: "9232eef2-f66b-4a63-94dd-448271e9d4d0", title: "Dr"}
    1: {id: "3d27249e-d825-4e51-8032-0ffbe8ec839d", title: "Miss"}
    2: {id: "01d4f5c1-f19f-4390-9e01-7cd4cd501d07", title: "Mr"}
    3: {id: "20b9bb71-fa48-4597-ab91-0028e7cb123f", title: "Mrs"}
    4: {id: "89029583-6549-45a3-93fe-6ec32a73381e", title: "Ms"}
    length: 5

When I perform a loop I get the following results for title:

11:50:24.320 stage-1.php:241 Dr
11:50:24.320 stage-1.php:241 Miss
11:50:24.320 stage-1.php:241 Mr
11:50:24.320 stage-1.php:241 Mrs
11:50:24.320 stage-1.php:241 Ms
11:50:24.320 stage-1.php:241 undefined

So I console log the k

11:52:10.685 stage-1.php:241 0
11:52:10.685 stage-1.php:241 1
11:52:10.685 stage-1.php:241 2
11:52:10.685 stage-1.php:241 3
11:52:10.686 stage-1.php:241 4
11:52:10.686 stage-1.php:241 clean

My code is this:

$.ajax({
    type: "GET",
    url: "/assets/core/php/ajaxCalls/optionFields/getData-v2.php",
    dataType: "JSON",
    data: {
       optionFieldTypeID: "bb5ac90b-22c0-438d-8b75-d2cb23bb6df3"
    },

    success: function (response) {
        console.log(response);
        for (var k in response) {
             console.log(response[k]["title"]);
             console.log(k);
         }
    }
  });

I guess I'm doing something really obviously wrong but can't see it - any ideas?

Michael Bellamy
  • 543
  • 1
  • 8
  • 16
  • 1
    Does it show the expected output if you write `response.forEach( function(value, idx) { console.log(value.title); console.log(idx); })`? – t.niese Oct 11 '18 at 11:02
  • Thanks, yes it does... ?? Can you explain why that works and my code doesn't please? – Michael Bellamy Oct 11 '18 at 11:03
  • 1
    I can't tell you why the your `response` object has an iterable key with the name `clear`, but it won't show up for `console.log(response)` because the log functions sees it is an array, and will show only the items in the array and the `length` property. `for..in` will iterate over all iterable key and is as of that not recommended for arrays, `forEach` on the other hand is a function provided by the Array to iterate over its elements. – t.niese Oct 11 '18 at 11:06
  • 1
    @MichaelBellamy you could also try [for ... of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) – barbsan Oct 11 '18 at 11:08
  • Great thank you for that explanation! – Michael Bellamy Oct 11 '18 at 11:12
  • Thanks barbsan - that works perfectly too. – Michael Bellamy Oct 11 '18 at 11:18

0 Answers0