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

"Converting PostgreSQL data into a PHP array with the column serving as the index

Is it possible to return a JSON object directly from a PostgreSQL query? Let's say the query produces results like this: who count ================= mary 2 had 9 a 12 lamb 9 The database has columns "who" and "count." I ...

The image displayed by the @vercel/og API route is not appearing correctly

I am currently facing an issue with my Next.js app hosted on Vercel Edge while trying to set up the Vercel/og package. You can find more information about it here: https://vercel.com/docs/concepts/functions/edge-functions/og-image-generation Upon loading ...

Ensure that each item rendered in a VUE.js v-for loop is distinct and not repetitive

I have obtained a JSON formatted object from a Web API that contains information about NIH funding grants. Each grant provides a history of awards for a specific researcher. My goal is to display only the latest award_notice_date for each unique project ...

What is the process for converting blog content into JSON format for export?

Currently, I am immersing myself in the world of blogging and web development simultaneously. My focus now lies on mastering JSON for which I am striving to devise a method that will enable me to export my entire blog content first to JSON and then XML. Th ...

How can you tell if a specific keyboard key is being pressed along with the CTRL button?

Is there a way to call functions when a specific key is pressed along with the CTRL key (on a Windows system)? While testing for a particular keyCode, I used event.keyCode. I researched the codes assigned to each key and assumed that 17 + 73 would represe ...

Guide on how to selectively add middleware such as multer to a fresh express router

For a previous project, I set up a router and utilized multer for handling file uploads. I was able to apply the multer middleware selectively on specific routes as shown below: var router = express.Router(); var multer = require('multer'); var ...

When extracting data, I am only receiving the initial row from the database, but I specifically require the latest row that was added in the database

I am working with a JSON data structure to fetch information from a database. However, the current implementation only retrieves the first row from the database whereas I specifically need to get the most recent row that was inserted. Here is my Java clas ...

Discovering user activity through rooms within SocketIO

My goal is to trigger an event when a user switches between online and offline status. The challenge arises from the fact that a user may have multiple tabs open, making it ineffective to track their connection status using on('connect') and on(& ...

Encountering a Mongoose issue while attempting to load model files from a separate Mean.js project using the require function

I am currently working on a Mean.js project and in the process of familiarizing myself with this environment. To conduct some experiments, I created a parallel project for testing purposes in a separate folder where I am not using the Mean.js framework but ...

Make jQuery fire an event when the "enter" key is pressed

I'm trying to create an event that will trigger when the "enter" key is pressed. I've been using this code, but for some reason it's not working and I can't figure out why. After searching everywhere, I came across this snippet that see ...

Looking to show an image when a checkbox is ticked and hide it when it is unticked in HTML?

How do I make a specific image appear when a user clicks on a checkbox? I'm unsure if I should use jQuery, Ajax, or another method. What is the best approach for this task? Your assistance would be greatly appreciated. I have successfully created the ...

Using an array as a route parameter triggers a "Expected to not repeat" warning

Every time I attempt to set up a router-link with an array as the parameter, the link functions properly but triggers the following warning : "Missing param for named route "start-run": Expected "files" to not repeat, but received ["aaa"] router.js .. ...

Perform the action when the button is clicked

I'm struggling with finding a solution to this problem. I have an input field and a submit button. My goal is to update the value of a variable to match the value in the input field when the submit button is clicked. Additionally, I need to execute a ...

Implementing ajax functionality for a form component in vuejs

I am currently working with a Vue.js component that serves as a form with a single field for an email input. The default value of this field, "email", is provided to the component by the parent as a prop. Upon form submission, I need to trigger an event to ...

Immerse yourself in a world of virtual reality with the cutting-edge VR Vide

Currently, I am in the process of developing a virtual panoramic tour that features various panoramas linked together with hotspots. Each panorama contains a video hotspot that plays a video. However, I have encountered an issue where every time a new sce ...

Leveraging the power of node.js, express, and handlebars to seamlessly render multiple views within a

I'm interested in finding out if there is a way to render multiple views using the res.render() function or another method. In the home.handlebars file, I currently have the following code: <h1>Home</h1> and I would like to display it i ...

The functionality of toLowerCase localeCompare is restricted in NuxtJs VueJs Framework

Encountered a peculiar issue in NuxtJs (VueJs Framework). I previously had code that successfully displayed my stores in alphabetical order with a search filter. When I tried to replicate the same functionality for categories, everything seemed to be work ...

Node.js - Hitting maximum call stack size limit despite using process.nextTick()

I am currently developing a module for creating "chainable" validation in Express.js: const validatePost = (req, res, next) => { validator.validate(req.body) .expect('name.first') .present('This parameter is required') ...

The <input> element is not functioning as expected when attempting to use it as a button. I am struggling to find the solution to

My HTML file contains: <!Doctype HTML> <html> <head> <title>Orange’s Game</title> <meta charset="utf-8"> <script src="game.js”></script> </head> <body> <input type="button ...

Converting JSON data into XML format

When I am converting JSON Values to XML, instead of getting JSON properties as elements of XML, I am receiving "title":"source". The desired output should be <title>source</title>. Can you help me identify what mistake I mig ...