Everybody, good afternoon, everybody,
I’m trying to access the attributes of a javascript object array via ajax, but I’m not succeeding, can anyone see where I’m going wrong?
My ajax call is like this:
$("#cbx1").on("change", function() {
var checkbox = $("#cbx1").val();
console.log(checkbox);
if(checkbox == "TF") {
var url = "/listar-perguntas?area-tematica=" + $(this).val() + "&montar-navegadores=true";
console.log("bateu aqui 1"+url);
} else {
var url = "/listar-perguntas?area-tematica=" + $(this).val();
console.log("bateu aqui 2"+url);
}
$.ajax({
type:'GET',
data : "",
url: url,
contentType: "application/json; charset=utf-8",
success: function(data) {
console.log(data);
let text = "<input>"
for (let x in data) {
text += "<label>" + data[x] + "</label>"
}
text += "</input>"
document.getElementById("temaFederal").innerHTML = text;
},
error: function(data){
console.log(data.statusText);
}
});
});
In my html it looks like this:
You have to first search for the object in which your label is stored. That is on the 10th position in the list. If the element is gonna be always on the last position you can simply do data[data.length -1] and that will select the last object on your list on root level. Once you have selected the object then you’ll need to do data[data.length - 1]?.teamnavigator?.bucket and that will give you the list on which your labels are stored. You can now iterate over this list.
Other wise you may search for the element first and then get your bucket list like this
const data = [
{ pergunta: 'lorem ipsum', guid: '1111'},
{ pergunta: 'lorem ipsum', guid: '1111'},
{ pergunta: 'lorem ipsum', guid: '1111'},
{ pergunta: 'lorem ipsum', guid: '1111'},
{ pergunta: 'lorem ipsum', guid: '1111'},
{
areatematicanavigator: {},
temanavigator: {
bucket: [
{
key: 'key',
label: 'label',
},
{
key: 'key',
label: 'label',
}
]
}
}
]
const objectOfInterest = data.find(item => 'temanavigator' in item)
const buckets = objectOfInterest.temanavigator.bucket
for (let index in buckets) {
console.log(buckets[index].label);
}
Edit: This is my first reply on stackoverflow. Pardon me for my silly mistakes.