0

I have a JSON object returned via ajax. When I try to access an array of strings in the response, I get undefined. I can see from the console log that the array exists and is populated.

$.ajax({
  type: 'GET',
  url: url,
  dataType: 'JSON'
}).done(function( response ) {
  $.each(response, function(){
    myConcatenatedTags = ''
    console.log(this);
    console.log(this.tags);
    for (var tag in this.tags) {
      myConcatenatedTags += tag;
    }
  });
});
console.log(myConcatenatedTags);

Response object

Object
    _id: "598be40d9c7685725199cea3"
    comments: "sometext"
    number: "sometext"
    quote: "sometext"
    source: "sometext"
    tags[]: Array[3]
        0: "tag1"
        1: "tag2"
        2: "tag3"
        length: 3

Yet console.log(this.tags); results in undefined, and console.log(myConcatenatedTags); prints an empty array.

If I try to access an index:

console.log(this.tags[0]);
// response
// Uncaught TypeError: Cannot read property '0' of undefined

What gives?


Update

The problem was how I was referencing the element.

Elements get referenced like so: this.source

But lists get referenced as a key, rather than with a dot notation: this["tags[]"]

And a console.log of this["tags[]"] looks as expected:

console.log(this["tags[]"]);
// ["tag1", "tag2", "tag3"]

Additionally, the mark for duplicate is inaccurate, as the access was in the .done callback. How do I get this removed?

modle13
  • 1,242
  • 2
  • 16
  • 16
  • what does `typeof response` shows you ? – Ulysse BN Aug 10 '17 at 14:48
  • `console.log(typeof(response));` gives me `object` – modle13 Aug 10 '17 at 14:51
  • 1
    Hum the duplicates doesn't look really related to OP's question: everything he gets is in the callback of done function – Ulysse BN Aug 10 '17 at 14:56
  • I considered that this was due to the asynchronous nature, but I'm confused why I'm able to log non-array elements of the response. For example, `console.log(this.source);` shows exactly what I would expect: `sometext`. So why am I unable to access the array? – modle13 Aug 10 '17 at 14:58
  • well I'm not sure what your this refer to. I had an answer related to your use of `$.each` which is wrong since you need an array, not an object. Instead you could use [`for...in`](//mdn.io/for...in), or loop over `Object.keys(response)` or if you are using lodash, `_.each` handle this pretty well – Ulysse BN Aug 10 '17 at 15:01
  • `this` refers to the current index of the response object in `$.each(response, function(){` – modle13 Aug 10 '17 at 15:06

1 Answers1

0

Seems that console.log(tags) is called before the function .done() has been executed.

Roberto Russo
  • 834
  • 10
  • 22