What is the best way to iterate over a JSON array object within an AJAX response using the 'each' function?

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?

Answer №1

It appears that the console.log(tags) statement is being executed prior to the completion of the function .done().

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

What is the process for posting an image from a URL in a Wordpress blog?

I am currently working on developing a web page using Gutenberg that includes both text and an image. The challenge I'm facing is that I need to download the image from a URL, import it into the media library, and then display it on the generated page ...

What methods can I use to avoid unnecessary array elements from being generated in Javascript?

When working in PHP, performing the following code: $var = array(); $var[5000] = 1; echo count($var); Will result in the output of 1. However, in JavaScript, missing elements are created. <script type="text/javascript"> var fred = []; f ...

"Encountering an error stating 'SyntaxError: Unable to use import statement outside of a module' when attempting to import a module that itself imports another module for side

I'm currently working on writing Jest tests for my TypeScript code. To ensure compatibility with older browsers, I have included some polyfills and other necessary imports for side effects. Here is a snippet of my code (variables changed for anonymit ...

Retrieve server responses in Javascript following a request initiated by Javascript

Can someone help me with my JavaScript function that sends a request to an aspx page? Here is the code: var xhr = ("XMLHttpRequest" in window) ? new XMLHttpRequest() : new ActiveXObject("Msxml3.XMLHTTP"); xhr.open("GET", 'http://www.example.net/ ...

What is the best way to iterate through a contacts array to generate a new array containing different objects with their own unique properties?

I have been exploring a way to transform an array by extracting specific properties. After successfully retrieving my contacts from my phone, I am aiming to restructure the data in a more organized format. How can I iterate over Array In and generate Array ...

I'm looking to transfer my stringified object into the HTML body. How can I achieve

When sending an HTML file to a client using the res.write() method, I also need to include an object within the HTML. However, when I stringify the object and add it along with the HTML, the JSON object ends up outside of the HTML structure. I require the ...

Using Kinetic JS to overlay a PDF file with an additional layer

I am seeking to overlay a layer on top of a PDF file (using PDF JS) with the help of Kinetic JS. This layer will be utilized for adding annotation comments to the PDF file. However, my issue lies in the fact that each PDF document's canvas has differ ...

Ways to transfer the jQuery variable from one PHP document to another file?

I am trying to pass a jQuery variable from one PHP file to another and facing some challenges in the process. My approach involves using AJAX to send the variable to the server in page1.php and then retrieving it with PHP in page2.php In page1.php, $.aj ...

Sending JSON data to an external API using .NET Core results in an error message stating "Unsupported Media

I'm currently working on developing a middleman API that is responsible for logging calls and other details made by internal users to an external API. However, I have encountered an issue. Whenever I attempt to make a POST request to the external API ...

Is there a way for me to adjust the font size across the entire page?

Most CSS classes come with a fixed font-size value already set. For instance: font-size: 16px font-size: 14px etc. Is there a way to increase the font size of the entire page by 110%? For example, font-size: 16px -> 17.6 font-size: 14px -> 15.4 ...

What is the best way to trim a double precision number in PostgreSQL while retaining only the first two decimal places?

Seeking a way to trim double precision values while constructing JSON using the json_build_object() function in PostgreSQL 11.8, but have been unsuccessful so far. Specifically, I want to truncate the number 19.9899999999999984 to only two decimals without ...

Does the size of a JavaScript heap, when it's big but not enough to cause a crash, have the potential to slow down a website, aside from just having an

Utilizing angular material dialog, I have incorporated a mat stepper with three tables (one per step), where one or two of them may contain an extensive amount of records. I have already integrated virtual scrolling to improve performance. However, when ...

Creating personalized JSON formatting in PHP by utilizing JOIN operation from MySQL database

As I embark on creating a project time tracking tool, I find myself in unfamiliar territory with JOINS. My expertise lies more in non-relational databases. In my MySQL database setup, I have two tables - "Projects" to store project information and "Projec ...

What is the proper way to terminate a Promise.all() in Angular 2?

My current sign-up process involves a Promise.all() being made on every "next" click, resulting in multiple http requests. However, when users quickly click through the process, these requests start to pile up and cause issues with my app. Is there a way ...

Issue with THREE.CubeTextureLoader where edges appear 1px too small

My latest project involved creating a panorama cube using THREE.CubeTextureLoader: pano = [ 'scenes/4/2048/px.jpg', 'scenes/4/2048/nx.jpg', 'scenes/4/2048/py.jpg', 'scenes/4/2048/ny.jpg', 'scenes/4/ ...

ReactJS popover element - property pushing and event management

I'm currently developing a reactjs application, and I'm working on creating a modular popup component. The goal is to have the button appear as a combination of a badge and an icon, triggering the popup menu on hover rather than on click. Here i ...

Utilizing Ajax for dynamic PHP result determination

HTML CODE <div class="card text-center pricing-card mb-20"> <ul class="list-group list-group-flush"> <?php $gbewas = mysqli_query($con,"SELECT * FROM price"); while($okks = mysqli_fetch_array($gbewas)) { ?> <li cla ...

What is the reason behind div elements shifting when hovering over a particular element?

Currently, I have floated all my div elements (icons) to the left and margin-lefted them to create space in between. I've displayed them inline as well. However, when I hover over one element (icon), the rest of the elements move. Can you please help ...

Importing JSON files dynamically in Typescript with Quasar/Vue using different variable names

Currently, I am in the process of developing an application utilizing the Quasar framework with Typescript. Managing a large number of JSON files for dynamic import has proven to be quite challenging due to the impracticality of manually importing hundreds ...

Listen for an event on a button to show a specific div

Looking to have a div appear when the user clicks on a button. //html-code <div class="col-md-4"> <h4 class="service-heading">Social Media</h4> <p class="text-muted">This is the first line of text.</p& ...