The code malfunctions following the maintenance

Recently, I started learning JavaScript and trying to improve the readability of my code by moving away from inline functions. I have a piece of code that iterates through a JSON array containing comments and then appends those comments to the DOM. Strangely, when my code is "messy" it works fine, but as soon as I clean it up, it stops functioning.

Can anyone help me figure out why? Here's the "messy" version:

var myCommentArray = [
    {
        _id: "888888888888888888",
        index: 1,
        name: "Perez",
        message: "First Comment .......",
        subject: "enim officias",
        replies: [ // this comment has replies (just 1 even though it's an array)
            {
                _id: "77777777777777777777",
                index: 0,
                name: "Reply to First Comment Ines for Perez",
                message: "...",
                subject: "reply subject consequat"
            }
        ]
    },
    {
        _id: "999999999999",
            index: 0,
            name: "Shelton",
            message: "2nd Comment....a",
            subject: "enim irure",
            replies: null // this comment has no replies which makes it null, better than an empty array
    },
    {
        _id: "666666666666666666",
        index: 2,
        name: "Perez",
        message: "3rd Comment.......",
        subject: "enim officias",
        replies: [
            {
                _id: "55555555555555555555",
                index: 0,
                name: "1st Reply to 3rd Comment",
                message: "...",
                subject: "reply subject consequat"
            },
            {
                _id: "44444444444444444444",
                index: 1,
                name: "2nd Reply to 3rd Comment",
                message: "...",
                subject: "reply subject consequat"
            }
        ]
    }
];

var stringedArray = JSON.stringify(myCommentArray);
var parsedCommentArray = JSON.parse(stringedArray);

$.each(parsedCommentArray, function (i, val) {
    var currentComment = parsedCommentArray[i];
    var commentsFormat = '<br> <div class="comment-avatar media-left"> <img src="http://placehold.it/50x50" alt="avatar">' +
        '</div><div class="comment-content media-body clearfix"> <div class="comment-avatar media-left"></div><h3 class="media-heading">' +
        currentComment.subject + '</h3> <div class="comment-meta">By ' + currentComment.name + '</div> <div class="comment-body"> <p>'
    + currentComment.message + '</p><a href="#" class="btn btn-gray more  reply">' +
        '<i class="fa fa-reply"> </i> Reply </a> </div> </div>';
    $('.comments').append(commentsFormat);
});

Here's the "clean" version:

 sabio.page.startUp = function () {
     var myCommentArray = sabio.page.getMyArray();

     var obj = JSON.parse(myCommentArray);

     $.each(obj, sabio.page.proccessComments);

     $("#submissionButton").on('click', sabio.page.handlers.onSubmit);

 }


 sabio.page.proccessComments = function (i, currentComment) {

    var commentsFormat = '<br> <div class="comment-avatar media-left"> <img src="http://placehold.it/50x50" alt="avatar">' +
         '</div><div class="comment-content media-body clearfix"> <div class="comment-avatar media-left"></div><h3 class="media-heading">' + currentComment.subject + '</h3> <div class="comment-meta">By ' + currentComment.name + '</div> <div class="comment-body"> <p>' + currentComment.message + '</p><a href="#" class="btn btn-gray more  reply">' +
         '<i class="fa fa-reply"> </i> Reply </a> </div> </div>';

      $('.comments').append(commentsFormat);
  }


  sabio.page.handlers.onSubmit = function () {
      $(".comments").toggle();
      $('html, body').animate({
          scrollTop: $(".comments").offset().top
      }, 2000);

  }

  sabio.page.getMyArray = function () {
      var myArray = [{
          _id: "888888888888888888",
          index: 1,
          name: "Perez",
          message: "First Comment .......",
          subject: "enim officias",
          replies: [ // notice this comment has replies (just 1 but it is still an array)
          {
              _id: "77777777777777777777",
              index: 0,
              name: "Reply to First Comment Ines for Perez",
              message: "...",
              subject: "reply subject consequat"
          }]
      }, {
          _id: "999999999999",
          index: 0,
          name: "Shelton",
          message: "2nd Comment....a",
          subject: "enim irure",
          replies: null // notice this comment has no replies and as such is null. this is better than an empty array
      }, {
          _id: "666666666666666666",
          index: 2,
          name: "Perez",
          message: "3rd Comment.......",
          subject: "enim officias",
          replies: [{
              _id: "55555555555555555555",
              index: 0,
              name: "1st Reply to 3rd Comment",
              message: "...",
              subject: "reply subject consequat"
          }, {
              _id: "44444444444444444444",
              index: 1,
              name: "2nd Reply to 3rd Comment",
              message: "...",
              subject: "reply subject consequat"
          }]
      }];

      return myArray;

  }

Answer №1

Instead of using JSON.parse() to parse your .getMyArray() method's object, you can directly iterate over it. There is no need to convert it into a JSON string. Simply do the following:

var myCommentArray = sabio.page.getMyArray();
$.each(myCommentArray, sabio.page.proccessComments);

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

Implementing a callback function following the completion of file reading in Phonegap

I have been facing this issue for quite some time now and I need assistance in finding a solution: When it comes to developing an android app, I rely on the phonegap framework. There is an async function called readFromFile() that reads a json file store ...

Modifying table background color using AJAX and jQuery?

Scenario: My web page is designed to automatically search for a specific cell input by the user. If the cell has been input with a value, the table's background color will turn red; otherwise, it will remain green. Currently, the table has not been p ...

A method in JQuery to replace an input with a select element is by using the replace

I have multiple input fields with pre-existing values. My goal is to replace these inputs with select dropdowns that have the same options while retaining the original values. Here is the current HTML structure: <span id="span1"> <input type=" ...

Locate and modify a specific element within an array of objects

Currently, I am working with an array that looks like this: arr = [{id:'first',name:'John'},{id:'fifth',name:'Kat'},{id:'eitghth',name:'Isa'}]. However, I need to add a condition to the array. If ...

a comparison tool for nested dictionaries that does not require conversion to sets

I have a task that has piqued my interest for the upcoming months. It presents quite an intriguing challenge and has the potential to be applied in various scenarios involving systems that handle extensive json data. To tackle this, I've created a un ...

Leveraging Javascript Modules within a Typescript Vue Application

The issue at hand I've encountered a problem while attempting to integrate https://github.com/moonwave99/fretboard.js into my Vue project. My initial approach involved importing the module into a component as shown below: <template> <div&g ...

Is there a way to merge two separate on click functions into one cohesive function?

I currently have two separate onclick functions as shown below. They are functioning properly but I am considering combining them for optimization purposes. Essentially, clicking on xx displays certain elements, hides others, and adds a class. Clicking o ...

Retrieving specific value from a Parent Controller in AngularJS using UI Router

I have a request to display the value stored in $scope.resAVal on my index.html page. This value is accessible within the RootCtrl. index.html <!DOCTYPE html> <html ng-app="plunker"> <head> <!-- any required JavaScript librarie ...

Clicking on buttons in the header does not lead to the intended section when scrolling

I have just completed a website project for a Udemy course, following all the instructions provided. However, I am facing an issue with the functionality of two buttons on my site. I want these buttons to scroll to specific sections when clicked. The "I&ap ...

A method designed to accept an acronym as an argument and output the corresponding full name text

Having trouble with my current task - I've got an HTML file and external JS file, and I need a function that takes an element from the 'cities' array as input and returns a string to be used in populating a table. I've set up a functio ...

"Unlocking the Power of mediaElementjs: Easy Steps to Accessing the Player Instance

I'm facing a small issue with the MediaElement.js player. To access the player instance, I usually use the following code (which works in HTML5 compatible browsers): // Retrieve player this.playerId = $('div#shotlist-player video').att ...

Managing dynamically appearing elements in Ember: Executing a Javascript function on them

I'm currently working on a project in Ember and facing an issue with calling a JavaScript function when new HTML tags are inserted into the DOM after clicking a button. Below is a snippet of my code: <script type="text/x-handlebars" id="doc"&g ...

Creating a callback API in Parse to retrieve a JSON response from an external API: A step-by-step guide

Greetings to all Stackoverflow developers. I am embarking on the journey of working with Parse and integrating third party services via PHP API. I have successfully been able to post data and retrieve responses from these APIs, but now the third party req ...

Can a Draft-4 JSON schema be used to automatically create an HTML form?

When defining my schema, I often use features like oneOf. Is there a library available that can automatically generate an HTML form based on these definitions? ...

Implementing Node Express 4 to efficiently handle response generation from successive API requests

I'm currently in the process of developing a NodeJS server using Express4. The main purpose of this server is to act as a mediator between my frontend Angular app and a 3rd party API. I've set up a specific path that my frontend app can request, ...

The execute command within a function is malfunctioning in Python 3.5

Currently, I am working on a python program that aims to parse JSON files based on their tags using the Python `exec` function. However, I encountered an issue where the program fails when the `exec` statement is within a function. RUN 1: Exec in a functi ...

Using Ajax to trigger JSON-formatted HTML output

Issue with Populating Modal Window I am encountering difficulties while trying to populate a modal window dynamically with extended information retrieved from a mySQL database. Despite attempting various methods such as nested arrays, while loops, and for ...

Is there a way to eliminate text from a barcode image using JavaScript or TypeScript?

This is my unique html code <div class="pr-2" style="width: 130px"> <div *ngIf="!element.editing" > <span class="ss">{{element.barcode}}</span> </di ...

Learn how to easily set a radio button using Angular 4 and JavaScript

It seems like a simple task, but I am looking for a solution without using jQuery. I have the Id of a specific radio button control that I need to set. I tried the following code: let radiobutton = document.getElementById("Standard"); radiobutton.checke ...

Encountered an issue with trying to access the 'map' property of an undefined value while using Express and VueJS

Currently, I am in the process of developing a fullstack application utilizing Express, VueJS, and Mongoose. The app functions as a news feed platform. A couple of days ago, I encountered an error which was resolved with the help of your guidance. However, ...