Tips for iterating through an array of objects nested within other objects

Good afternoon everyone,

I’m having trouble accessing the attributes of a JavaScript object array through AJAX. Can anyone spot where I might be going wrong?

View image description

This is my AJAX call:

$("#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 appears as follows:

See image description here

Answer №1

To locate the object containing your label, start by searching for it in the 10th position on the list. If the element is consistently at the last position, you can use data[data.length -1] to select the final object at the root level of your list. Once you have identified the object, access the bucket where your labels are stored using data[data.length - 1]?.teamnavigator?.bucket. You can then iterate through this list.

Alternatively, you can search for the element first and retrieve your bucket list in a similar manner:

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);
}

Correction: This marks my debut response on stackoverflow. Please excuse any novice errors I might have made.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering the closest major urban area using geonames

One of my PHP functions retrieves the closest nearby city based on a given latitude and longitude: function findCity($lat, $lng, $username) { $json_url = "http://api.geonames.org/findNearbyPlaceNameJSON?lat=" . $lat . "&lng=" . $lng . "&us ...

What is the best way to extract Key:Value pairs from a JSON JArray?

I am currently working on a project where I need to extract some data from the following link: Highlighted below is a snippet of the JSON file: [{"id":6044586,"u":"ubergine","uid":"472505","a":"2011\/community\/users\/4\/7\/2&bsol ...

Tips for choosing a single checkbox from a set of multiple checkboxes in React.js

I iterated through a list of objects to generate table rows, each containing an input tag with the type set as checkbox. const [ isChecked, setIsChecked ] = useState(false); const handleChange = (e) => { setIsChecked(e.target.checked) ...

Incorrect footer navigation on my Vuepress website

I'm in the process of developing a vuepress single page application for showcasing and providing downloads of my personal game projects. When it comes to website navigation, I am aiming to utilize the native sidebar exclusively. This sidebar will hav ...

javascript has a funny way of saying "this is not equal to this" (well,

Sample 1 var Animal = function () { var animal = this; this.makeSound = function() { alert(animal.sound); } } var dog = new Animal(); dog.sound = 'woof'; dog.makeSound(); Sample 2 var Animal = function () { this.makeSound = ...

What is the method for displaying a file using a binary string as input?

Is there a way to display a PDF file from a binary string on a web browser? I know that for image files, we can use atob() and then <img src="data:image/png;base64,... But what about PDF files? Is there an equivalent method or syntax like ReadItAs("cont ...

Can Hapi-Joi validate a payload consisting of either an Array of objects or a plain Javascript object?

How can I create a schema to validate payloads for a post call that accepts either a single JS object or an array of objects to be saved in the database? JS object { label: 'label', key: 'key', help_text: 'text' } ...

Check the status of a server using Json with the help of Alamofire and SwiftyJson

When working with Alamofire and SwiftyJson to parse Json data in a Table View, I am able to successfully parse the result section but encountering difficulties in fetching the status section using Swifty JSON. The main question is how can I correctly parse ...

Retrieve JSON data from a WordPress site that is powered by WooCommerce, using basic authentication

I am in the process of creating an Android application that retrieves product data from a WordPress site. The website has the Woocommerce plugin installed. I have been able to successfully obtain the JSON data using Postman software and basic authenticat ...

Utilizing JavaScript to assign class names to dynamically created elements from objects

I specialize in javascript and am working on adding the CSS class .is-slideUp to each card__item element created from a data object, in order to achieve a sliding-up animation effect. Although the .is-slideUp class name appears in the console, it does not ...

What could be the reason for JSON.parse not returning the expected outcome?

My code is as follows: var jsonStr = (JSON.stringify(data, ['flightPositions', 'flightId', 'positions', 'lat', 'lon', 'date'], 4)); alert(jsonStr); var jsonObj = JSON.parse(jsonStr); alert(jsonO ...

Refreshing a page occurs every 30 seconds or upon the user submitting a form

My PHP page consists of various includes for different sections of a video website. One of these sections is a comments area where users can submit their feedback to a database successfully. However, I want to ensure that only the specific included page/di ...

Modify the database entry only if the user manually changes it, or temporarily pause specific subscriptions if the value is altered programmatically

After a change in the viewmodel, I want to immediately update the value on the server. class OrderLine { itemCode: KnockoutObservable<string>; itemName: KnockoutObservable<string>; constructor(code: string, name: string) { ...

Tips for retrieving selected items in an array object

Within my UI, I have a select field that, on change, populates corresponding data in a div with nested ul and li elements. What I am attempting to achieve is to convert the selected items within the list (which include checkboxes) into an object of arrays ...

What are the benefits of using default ES module properties for exporting/importing compared to named module properties?

Currently studying the Material UI documentation, I came across this statement: It is noted in the example above that we used: import RaisedButton from 'material-ui/RaisedButton'; instead of import {RaisedButton} from 'material-ui&apo ...

In AngularJs, use ng repeat and ng switch to dynamically generate and display tables

I need help rendering a table with two columns using angularjs directives. <table> <tr ng-repeat="message in messages" > <td ng-switch-on="message.network" ng-switch when="twitter" ng-controller="TweetController"> <span> ...

Using an Angular interface for an HTTP request: The statusText message reads as "Error: Unable to Determine."

I've been working on calling an API as an example in Angular using an interface. The API I'm trying to access is located at https://jsonplaceholder.typicode.com/posts. Unfortunately, I encountered the following error message: ERROR HttpErrorResp ...

Using Node.js to invoke an identifier loop

Having some trouble with this loop. Should I include variable c in the loop as well? Let me provide some context: there is a table and child(i) changes for every row. The SelectorT receives a sentence structured like this: Now\nIs\n09:00\n4 ...

After removing an item from the component in reactJS, the immediate rendering of the dynamic component does not seem to be functioning correctly

I am currently creating a dynamic automobile inventory website from scratch using React.js, Express.js, and MongoDB. The data has been successfully loaded from the database and displayed in a tabular format on the client side. My next task is to enable use ...

Show the time with AM/PM without displaying the year, month, or day

Currently, I am struggling to show the time as AM when my website loads using the format mm-dd-yyyy --:-- AM in a datetime-local input. The value attribute of datetime-local is causing some confusion for me. ...