Add new items to an array, with the most recent item being the last

I have encountered an issue while looping through an array of objects. Depending on their type property, I create a different class and append it to an array. However, the problem is that the output always consists of duplicates of the last class created.

// Creating Elements from Content
// Unique id's are generated using UUIDV4.
self._elements = new Array

let e;
self.content.page_data.forEach(cont => {
    switch (cont.type) {
        case 'paragraph':
            e = new Paragraph()
            console.log(e.element.id)
            self._elements.push(e)  
            break;

        case 'title':
            console.log('title')
        return 
    }
})
console.log(self._elements)

Upon troubleshooting, I discovered that the issue lies not with e, as each instance is indeed different. The problem arises once these instances are pushed/added to the array. Specifically, the problem occurs only when instances of Paragraph() are created. Other items in the array, such as text, remain the same but still duplicate the last class.

I would appreciate if someone could clarify what I might be missing here?

EDIT - Class for Paragraph

class Paragraph {
  constructor(value = '') {

    self._element = template_paragraph.cloneNode(true).content.children[0];
    const quil = self._element.children[0].children[1].children[0];
    self.quill = new Quill(quil, {
      modules: {
        toolbar: [
          [{ header: [1, 2, false] }],
          ['bold', 'italic', 'underline'],
          [{ list: 'ordered' }, { list: 'bullet' }]
        ]
      },
      placeholder: 'Compose an epic...',
      theme: 'snow'  // or 'bubble'
    })

    self._element.id = uuidv4()
  }

  get element() {
    return self._element
  }

  set_content(content) {
    // Set quill value
    if (!content) return
    //self.quill.setContents(content)
  }
}

The Quill functionality interacts seamlessly with my cloned HTML elements. Hopefully, this additional information will prove helpful in resolving the issue.

Answer №1

When working with JavaScript, it's important to remember that the keyword is this, not self (which is more commonly used in Python). While self is not a keyword in JavaScript, some people opt to use it as a regular variable name by manually assigning var self = this; somewhere for convenience. However, it is typically recommended to stick to using this and following the standard conventions based on this Stack Overflow discussion.

To ensure clarity and best practices, consider replacing instances of self with this in your code.

Answer №2

I present a counterexample to challenge your assertion. It appears that your code is functioning correctly, suggesting that the issue lies elsewhere, likely within your Paragraph class.

By making adjustments to the underlying framework (including self, content, page_data, etc.) and the Paragraph class, I can prove that your code (as provided) operates as intended. Each element within self._elements is indeed unique, notably possessing distinct id values.

// [[[ MOCK FRAMEWORK TO CONFIRM FUNCTIONALITY OF YOUR CODE
let self = { content: { page_data: [
  {type:'title'},
  {type:'paragraph'},
  {type:'paragraph'},
] } };
let nextUnusedId = 101;
let Paragraph = function () { this.element = { id: nextUnusedId++ } }
// ]]]

// Generate Elements from Content
// Unique ids generated by UUIDV4.
self._elements = new Array

let e;
self.content.page_data.forEach(cont => {
    switch (cont.type) {
        case 'paragraph':
            e = new Paragraph()
            console.log(e.element.id)
            self._elements.push(e)  
            break;

        case 'title':
            console.log('title')
        return 
    }
})
console.log(self._elements)

Answer №3

Consider using a fresh variable declared within the loop's scope

// Generate Elements from Content
// Unique ids are generated using UUIDV4.
self._elements = new Array

self.content.page_data.forEach(cont => {
    switch (cont.type) {
        case 'paragraph':
            var e = new Paragraph()
            console.log(e.element.id)
            self._elements.push(e)  
            break;

        case 'title':
            console.log('title')
        return 
    }
})
console.log(self._elements)

Based on your issue description, it seems like you have a single "reference" variable 'e' being reused in the array creation, leading to all references pointing to the last iterated object by the loop.

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

Updating JSON data in Node.js by adding a new object

I'm facing a situation where I have a JSON file acting as a database to manage users by adding, removing, and modifying them. Currently, I have the following code snippet: 'use strict'; const fs = require('fs'); let student = { ...

Simultaneously scroll through various div elements

Is there a way to synchronize scrolling across multiple div elements? I want the scroll position in one div to be reflected in all other divs. Since I am creating the div dynamically, I am using the function document.getElementsByClassName sub-category-co ...

Creating a Custom FlatList Content Container with React Native

Is it possible to customize FlatList items with a custom component? I want to create a setup where my FlatList items are encapsulated within a custom component similar to the following: <ScrollView pt={8} px={16} pb={128} > <Card e ...

Navigating through a intricate JSON dataset

Hello, I apologize for any language barriers as French is my native tongue. I am reaching out to seek assistance with navigating a complex JSON object using a loop in Javascript, particularly with JOINTJS. I am struggling to access the information I need ...

Managing waste: AngularJS service variable cleanup

I am a beginner in angularjs. Recently, I created an angularJS service based on the following diagram: https://i.sstatic.net/NifC5.png The Global Service acts as a way for controllers to communicate with each other. It holds data shared between parent an ...

Arranging strings in alphabetical order using Groovy

I've recently been delving into the world of arrays in Groovy. I'm currently figuring out how to sort an array of strings alphabetically. As of now, my code reads string input from the user and displays them in both order and reverse order: Syst ...

Guide to accessing and updating data in various tabs within a Google spreadsheet

I have two tabs named TAB A and TAB B. My goal is to iterate through TAB A and extract a set of values that I can then paste into TAB B. However, I encountered an error message saying, "Cannot read property 1, etc" function getValuesFromModal(form) { ...

storing Java command line arguments in an array

Hello, I am a complete beginner in Java and I have run into an issue when trying to use command line arguments as an array. For example, I attempted to write this code: double[] a = Double.parseDouble(args[0]); but it returned an error saying "cannot con ...

What is the method for incorporating a counter variable into a variable's name?

Here's my code, which I know is very inefficient: var slider1 = new Slider("#survey1", { precision: 2, value: 5 }) var slider2 = new Slider("#survey2", { precision: 2, value: 5 }) var slider3 = new Slider("#survey3", { precision: ...

Side Panel Extending Off Screen Upon Resizing

I'm encountering an issue with the sidebar on my HTML page. The problem arises when I click the 'Upload Data' button, causing the sidebar's header to extend beyond the screen if I resize the window. The only way to fix this is by refres ...

Node timers exhibiting unexpected behavior contrary to documented specifications

Feeling a bit lost with this one. I'm running Ubuntu and using nvm for node. I made sure to uninstall the version of node installed via apt just to be safe. node --version > v10.10.0 npm --version > 6.4.1 So, I go ahead and create-react-app a ...

Matching the height of table cells with the background height

I'm struggling with the height of a table cell that contains a background image. The width of the cell is set to be 100% of the page's width, and the image's background-size is also set to 100%. This setup makes the background image scale to ...

A guide on updating div IDs using jQuery sortable when an element is moved by the user

My goal is to use jQuery sortable to allow users to rearrange elements on a page by dragging and dropping them. Each div element has a unique ID, and when the user swaps elements, I want to update the IDs accordingly and alert the new order so it can be sa ...

Displaying PDF files on the internet without allowing them to be downloaded

How can I display PDF files on my website without allowing them to be saved or downloaded? Is there a way to prevent browsers from saving or downloading the PDF files? ...

Tips for creating a unique exception in AngularJS?

I have a customException.js script with the following service: app.service('CustomException', function() { this.CustomException1 = function (message) { if (!message) { message = "Custom Exception 1 occurred!"; } return { ...

Error: The function callback.apply is not a valid function (Node.js and Mongodb)

Encountered an error when adding the line "{ upsert: true }": Error message: TypeError: callback.apply is not a function // Accessing routes that end in /users/competitorAnalysisTextData // ---------------------------------------------------- router . ...

What is the method for retrieving the declared type value in TypeScript?

I've got a bit of a quirky question. So let's say I have a type declaration like this: type CardType = 'InformationCard' Can you think of any way to directly use CardType as a value? For example: console.log(CardType) ...

A guide to obtaining radar chart coordinates by utilizing the getValueForDistanceFromCenter method in Chart.js

I've been experimenting with creating radar charts using Chart.js. I have a good grasp on the basics, as shown in the simple chart below, but I'm looking to utilize the x y coordinates of the graph to position text directly on the canvas. After ...

Retrieve JSON data from an object using the Amplify Storage feature

I recently retrieved data from an object in an S3 Bucket using Amplify. export function amplify() { let key = "68a92d44-f25a-4bd8-9543-cc95369ae9a0"; return Storage.get(key + ".json", { download: true }) .then(function(result) { return ...

Discovering the method for keeping track of file changes and executing find-replace operations without registering it as an event within the monitored file

I am confused about why the output displays two lines when typing 'fizbuzz' into the test.txt file. I understand that it is performing a find and replace operation, but how can I avoid it being triggered by the watch function? const watch = requ ...