Creating an array from objects without manual effort

Greetings everyone, currently I am structuring my array in the following manner:

var piece1 = new DialoguePiece(null, questions[0], 0, 0, 4, 1);
var piece2 = new DialoguePiece(null, questions[1], 1, 0, 2, 3);
var piece3 = new DialoguePiece(scripts[1], null, 2, 1, 2, 2);
var piece4 = new DialoguePiece(scripts[2], null, 3, 1, 3, 3);
var piece5 = new DialoguePiece(scripts[0], null, 4, 0, 5, null);
var piece6 = new DialoguePiece(scripts[3], questions[2], 5, 4, 6, null);
var piece7 = new DialoguePiece(scripts[4], null, 6, 5, 7, null);
var piece8 = new DialoguePiece(scripts[5], null, 7, 6, null, null);

var pieces = [piece1, 
              piece2,
              piece3,
              piece4,
              piece5,
              piece6,
              piece7,
              piece8];

However, I am contemplating if there is a simpler approach to achieve this. For instance:

var pieces = GetObjectsByName(DialoguePiece);

Your insights would be greatly appreciated.

Answer №1

class DialoguePiece{
  static pieces = [];
  
  constructor(){
    DialoguePiece.pieces.push(this);
    // ...
  }
}

Instead of using a simple array to store the dialogue pieces, we can use a static property in the class itself. This makes it easier to reference and access the pieces:

for (let i = 0; i < 10; i++) {
  new DialoguePiece();
}

console.log(DialoguePiece.pieces);
// It's a standard array, so you can also map over it:
console.log(DialoguePiece.pieces.map(piece => piece.name || "doesn't exist"));

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

Automate populating input fields with data

I need help with a form that has four input boxes. Is it possible to automatically fill the remaining three input boxes with the value entered in the first box when the user clicks a button using JavaScript? Or should I aim to prefill the textboxes with ...

looking to retrieve the corresponding value of a specific array key

I am trying to determine the value of a complex array, but I keep getting values like 0,1,2,3,4,5 as answers. Here is the code snippet I am using to retrieve the state value of the array: var shardState = Object.keys(mydata.cluster.collections[collection ...

Pan motion gesture above HTML components

Is it possible to create a hovering effect over elements in a container using a pan gesture? https://i.sstatic.net/E6G56.gif Here's the HTML code: <div class="container"> <div class="item"></div> <div class="item"></div ...

Passing information from a directive to a controller using AngularJS

I am looking to display the progress of a file upload using a file reader. Here is the HTML code snippet I have: <md-progress-linear id="file-progress-indicator" md-mode="determinate" value="{{progress}}"></md-progress-linear> and below is m ...

Transmit information to PHP via JSON with Cross Domain communication

My code is server1 and PHP code is server2. These servers are not connected. What issues can arise from this setup? var req = new XMLHttpRequest(); req.open("POST", "http://www.example.com/form/data.php", true); req.setRequestHeader("Content-type", "ap ...

Make the checkbox font-weight bold when it is checked

Attempting to apply custom CSS to enhance the appearance of checkboxes using input and label elements. The goal is to make the font-weight bold when a user clicks on the checkbox, and then revert it back to regular if clicked again. Currently stuck on this ...

Introducing the new default in Google Chrome: Now accessing window.opener for target="_blank" links after rel="noopener" is the standard feature

Exploring a new attribute called rel="noopener", I discovered that it keeps opened windows unaware of their opener. After some experimentation, I consistently found window.opener === null, only to realize that this is now the default behavior in ...

Utilize environment variables to access system information when constructing an Angular 2 application

In order to build my Angular application, I want to utilize a single system variable. System Variable server_url = http://google.com This is how my Environment.ts file looks: export const environment = { production: false, serveUrl: 'http://so ...

Implementing a New Port Number on a ReactJs Local Server Every Time

As a newcomer to ReactJS, I recently encountered an issue while working on a project that puzzled me. Every time I shut down my local server and try to relaunch the app in the browser using npm start, it fails to restart on the same port. Instead, I have ...

Ways to conceal #div element from displaying in the href attribute within the anchor tag

My anchor tag has an href attribute that looks like this: <a onclick='loadReview(\"" + strexternalURL + "\");' href='#productName1'. When clicking on it, the URL appears as http://localhost:54986/Dealerlist.aspx#productName ...

Submit form data asynchronously using Ajax and serialize the form data before posting

I'm currently facing an issue with posting HTML form values in my code. Everything works fine except for the fact that I can't get it to post single quotes ' . I believe this problem is caused by the usage of serialize. I've attempted c ...

I desire for both my title and navigation bar to share a common border-bottom

As I embark on my journey into the world of HTML and CSS, my knowledge is still limited. Despite trying various solutions from similar queries, none seem to resolve my specific issue. What I yearn for is to have both my title and navigation bar share the s ...

Using ReactJS to trigger a timer function on a button click

Kindly Note: This is a unique query and not related to ReactJS - Need to click twice to set State and run function. The suggested solution there does not resolve my issue. This represents my original state: constructor(props) { super(props) this. ...

When refreshing a JavaScript array of objects, it creates duplicate entries within the array

Currently, I am developing a chat application within a Vue project and experimenting with different features. A fully-featured chat app must have the ability to live-update "seen" states. This means that when one user views the last sent message, the othe ...

Combining URLs in Angular 6 - A Step-by-Step Guide

How can I concatenate the commonUrl from CommonClass in Angular 6 for category.service.ts? common-class.ts export class CommonClass { constructor(public commonUrl : string = 'http://localhost:3000'){}; } category.service.ts import { CommonC ...

The results returned by the jQuery find() function vary across various pages

One interesting feature on my website is the header bar with a search function. I have implemented a function that involves resizing boxes to contain search results. On one specific page, this function works like a charm: $(".suggestionCategory").each(fu ...

Trigger the click event on the ul element instead of the li element using jQuery

Is there a way to make the click event only affect ul tags and not all li elements using jQuery? <!-- HTML --> <ul class="wrap"> <li>test1</li> <li>test2</li> <li>test3</li> </ul> I attemp ...

What is the cause behind the failure of this regular expression in JavaScript?

I have been struggling to make this code display "matched!" for the specific string. I've tried various methods but nothing seems to be working. Here's the HTML part: <div id="ssn">123-45-6789</div> And here's the JavaScript p ...

JavaScript detecting improper XHTML syntax

Is there an effective method to detect malformed XHTML within a string using JavaScript? Given that my page allows user-generated XHTML (from trusted users) to be inserted into the DOM, I aim to identify unclosed or overly closed tags. If found, I intend ...

What is the best way to retrieve the current directory of the executed javascript file?

My javascript file is located in a folder at this path: /httpdocs/wp-content/themes/themeName/users/js I have some PHP files in another directory within the same theme, where I need to send Ajax Requests: /httpdocs/wp-content/themes/themeName/users Is ...