After making an AJAX call, I have a JSON object as the response. However, when I try to access an array of strings within the response, I am getting 'undefined' in return. Strangely, the console log shows that the array does exist 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);
This is what the Response object looks like:
Object
_id: "598be40d9c7685725199cea3"
comments: "sometext"
number: "sometext"
quote: "sometext"
source: "sometext"
tags[]: Array[3]
0: "tag1"
1: "tag2"
2: "tag3"
length: 3
Even though console.log(this.tags);
should show the array, it returns undefined
. Similarly, console.log(myConcatenatedTags);
gives an empty result.
If I attempt to access an index directly:
console.log(this.tags[0]);
// response
// Uncaught TypeError: Cannot read property '0' of undefined
What could be causing this issue?
An Update on the Situation
The problem was actually related to how I was accessing the element in question.
Individual elements are referenced using dot notation, like this: this.source
However, when working with lists or arrays, they must be accessed by their key, not via dot notation. For example: this["tags[]"]
A console.log
of this["tags[]"]
displayed the expected output:
console.log(this["tags[]"]);
// ["tag1", "tag2", "tag3"]
Moreover, there seems to be confusion around marking duplicates, especially since the access was made inside the .done
callback function. How can this be rectified?