JavaScript - Display all comments

Here's the structure of my JSON data:

{
    "comment_ds": [
        {
            "c_user": [
                "Alice",
                "Alice",
                "Alice",
                "Alice",
                "Alice"
            ],
            "c_user_img": [
                "/media/accounts/1234567890/1234567890.jpg",
                "/media/accounts/1234567890/1234567890.jpg",
                "/media/accounts/1234567890/1234567890.jpg",
                "/media/accounts/1234567890/1234567890.jpg",
                "/media/accounts/1234567890/1234567890.jpg"
            ],
            "c_content": [
                "interesting",
                "brilliant",
                "amazing",
                "fantastic",
                "superb"
            ]
        }
    ]
}

I am extracting and rendering this data from an Ajax response using the following code snippet:

success: function(data) {
    comm_data = data['comment_ds'][0];
    var i = 0;
    Object.entries(comm_data).forEach(([key, value]) => {
    if (i < value.length){
        c_user          = comm_data["c_user"][i];
        c_content       = comm_data["c_content"][i];
        c_user_img      = comm_data["c_user_img"][i];

        comment = document.createElement('tr');
        comment.setAttribute('class','comment')
        $(comment).html(`
        <th class="comm_th_1"><img class="comm_user_image" src="${c_user_img}"><a class="comm_user">${c_user}</a></th>
        <th class="comm_th_2">${c_content}</th>
        <th class="comm_th_3"></th>`);
        $('.comm_cont').append(comment);
        }
        i+=1;
        });
        }
      }

Although it successfully displays the first three comments, it abruptly stops after that.

Even though value.length returns 5 when I console.log it, the incremental variable i seems to halt at 3.

Your input and suggestions are greatly appreciated.

Answer №1

To create a loop using the c_user property and the forEach method, simply utilize the indexer provided by the method.

Given that c_user, c_user_img, and c_content all have the same length, you can leverage this index to assign other corresponding values: c_user_img and c_content.

var data = {
    "comment_ds": [
        {
            "c_user": [
                "Alice",
                "Alice",
                "Alice",
                "Alice",
                "Alice"
            ],
            "c_user_img": [
                "/media/accounts/1234567890/1234567890.jpg",
                "/media/accounts/1234567890/1234567890.jpg",
                "/media/accounts/1234567890/1234567890.jpg",
                "/media/accounts/1234567890/1234567890.jpg",
                "/media/accounts/1234567890/1234567890.jpg"
            ],
            "c_content": [
                "nice",
                "awesome",
                "very cool",
                "great",
                "perfect"
            ]
        }
    ]
};

comm_arr = data['comment_ds'];
comm_data = comm_arr[0];

comm_data.c_user.forEach(function (user, index) {
  img = comm_data.c_user_img[index];
  content = comm_data.c_content[index];
  
  console.log(user, img, content);
});

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

Unlock the power of jQuery chaining with the val() method

My selected background color is set to: var _back = "#FF0000"; Why doesn't this code change the input field's background color: $("#input").val( _back ).css("background-color",$(this).val()); But this one does? $("#input").val( _back ) ...

A method for transforming each word in a string to begin with a capital letter

I'm not sure if my approach to solving this problem is correct: function capitalizeFirstLetter (string) { let stringArray = string.split(' '); for (let i = 0; i < stringArray.length; i++) { let firstLetter = stringArray[i ...

Encountering an issue when attempting to establish a connection to Redis using a cache manager within a Nest

Incorporating the NestJS framework into my project and utilizing Cash Manager to connect with Redis cache. Successfully connected with Redis, however encountering an error when attempting to use methods like set/get which shows 'set is not a function& ...

Challenges when using deep linking to URL with AngularJS ui-router

Recently, I encountered an issue after restructuring the folder organization of my AngularJS application. Although I believe this might be a distraction from the root cause, I moved a section of functionality to its own directory for better organization. A ...

Having trouble with Angular 2 and localhost/null error while attempting to make an http.get request?

In my Angular 2 webpage, I am using the OnInit function to execute a method that looks like this (with generic names used): getAllObjects(): Promise<object[]>{ return this.http.get(this.getAllObjectsUrl).toPromise().then(response => response. ...

Incorporate data into the input value rather than the div using Ajax technology

This ajax function is working perfectly, but I would like to modify the location where the result should appear. <script type="text/javascript"> function submitForm1() { var form1 = document.myform1; var dataString1 = $(form1).serialize(); $.ajax ...

Convert the list items into JSON format

<div class="col-xs-4 no-padding contenteditable-color" style="background-color: transparent;"> <ul class="ul-product"> <li class="li-product-page cars contenteditable" contenteditable="false">qweryt</li> </ul&g ...

Fancybox may be difficult to spot when using Safari

Currently, I am utilizing fancybox with the latest versions of jquery.min.js (3.3.1), jquery.fancybox.css (3.5.7), and jquery.fancybox.pack.js (3.5.7). Everything is functioning as expected on all browsers except for Safari. On Safari, the content within ...

Encountering an issue with Firebase Cloud Messaging

I am struggling to implement a push notification trigger whenever a document field is updated. As a newcomer to node.js, I am facing challenges in debugging what seems like a simple function. Below is the code snippet: // Cloud Functions for Firebase SDK ...

Trouble with Setting a Background Image in Ionic with Javascript and Angular

I'm having trouble getting my background image to display in this Ionic project using CSS. It works when I embed it directly into the HTML, but that's not an ideal solution. I vaguely recall something about using base64 for images, but I'm n ...

Expect a promise to be resolved in the RootCtrl of Angular using $http

One of the functions in my RootCtrl is responsible for calling an http api and returning the result. $scope.checkAccess = function(){ var result = MyService.me(); result.then(function(response){ console.log(response); if (response. ...

What is the best way to bind data to a textarea component and keep it updated?

I started using VueJS just a week ago for a new project. During this time, I have successfully created two components: * Account.vue (Parent) <!--This snippet is just a small part of the code--> <e-textarea title="Additional Information" ...

Utilizing AJAX to invoke a function

I'm having trouble explaining this, but I'll try my best. I created a function that calculates the remaining amount needed to qualify for free delivery based on different basket value thresholds. Whenever a product is added to the basket, the b ...

What is the best way to retrieve a value from this Ruby hash?

I am currently working with the Foursquare API and my goal is to retrieve the "id" value from the given hash [{"id"=>"4fe89779e4b09fd3748d3c5a", "name"=>"Hitcrowd", "contact"=>{"phone"=>"8662012805", "formattedPhone"=>"(866) 201-2805", "twi ...

What is the source of this error message "Exceeding maximum characters in string literal"?

Hey everyone! Sorry for the bother, but I'm a bit stumped on this issue. Within my view, I have the following code snippet: <fieldset> <dl> <dt> <label for="FormTypes">Form Type:</label> ...

Using React Material UI icon within an auto complete feature

https://i.stack.imgur.com/W3CmF.png I am struggling to incorporate the target icon into the autoComplete component. After reviewing the documentation, I have been unable to find a solution. In TextInput, a similar outcome can be achieved by implementing ...

Sending a JavaScript Array to PHP results in receiving Undefined or Disallowed Key Characters

I've been grappling with this problem for a few days now. I have an array in JavaScript that I need to send over to my PHP method. This is my PHP code: public function saveCampaignSendToMediaOwner() { $result = $this->input->post(); e ...

Retrieve name and value pairs from a JSON string stored in a MySQL database and insert them into another

In my MySQL database, I have a column called 'other' in 'table_one', which stores JSON strings. This table contains millions of records. A. My goal is to loop through 'table_one', extract data from the 'other' co ...

What are the issues with using AJAX in conjunction with a for-loop?

I'm currently developing a small application that needs to create work schedules and calculate hours: . I've written the function kalkulacja() to calculate the inputs for each row and output the results through ajax. However, I'm facing an i ...

Could someone clarify why EventEmitter leads to issues with global variables?

I recently encountered an error that took me some time to troubleshoot. Initially, I decided to create a subclass of EventEmitter In the file Client.js var bindToProcess = function(func) { if (func && process.domain) { return process.domai ...