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?