Is it possible to generate objects dynamically as the program is running?

Looking at the code snippet below, I currently have an array containing two JSON objects. However, if I need to create 20 objects, is there a more efficient way than manually writing each object in the array? Furthermore, is it possible to generate these objects during runtime and assign random values to them as they are being created?

I understand that JavaScript has its limitations when compared to object-oriented programming languages like Java or C#, where you could easily create objects from a single class and add them to a list.

var numbers = [
    {
    "x": 100,
    "y": 100,
    "visible": true,
    "value": 23
    },
    {
    "x": 150,
    "y": 100,
    "visible": true,
    "value": 19
    },
    ];

Answer №1

Firstly, it's important to note that JavaScript is indeed a legitimate object-oriented language. Secondly, JavaScript provides the flexibility of creating objects either through constructor functions or using object literals within loops. Thirdly, what you are dealing with in this scenario is not JSON; as stated by there is no actual JSON object.

That being said, here is one approach to achieve the desired outcome:

function getRandomInt(min, max) {
   return Math.floor(Math.random() * (max - min + 1)) + min;
}

var numbers = [];

for (var i=0; i < 20; i++) {
    numbers.push({
       "x": getRandomInt(0, 200),
       "y": getRandomInt(0, 200),
       "visible": true,
       "value": getRandomInt(0, 50)
    });
}

Alternatively, you can utilize a constructor function:

function MyObject() {
   this.x = getRandomInt(0, 200);
   this.y = getRandomInt(0, 200);
   this.visible = true;
   this.value = getRandomInt(0, 50);
}

var numbers = [];

for (var i=0; i < 20; i++)
   numbers.push(new MyObject());

Answer №2

let figures = [];

for(let j = 0; j < 30; ++j) {
    figures.push({
        a: Math.random(),
        b: Math.random(),
        show: Math.round(Math.random() * 10) / 20) % 3 == 0,
        val: Math.random()
    });
}

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

Python's nested if conditions allow for more complex conditions to be

In a specific scenario, I am required to validate certain conditions within the provided JSON data and then take action accordingly. You can view the json data here. The condition that needs to be checked is as follows: Iterate through the JSON and ident ...

Encountering problems when trying to mock values with Jest

I'm currently integrating Jest into an existing project that is already utilizing enzyme and jasmine. Although I have installed the jest packages and configured them initially, I am facing an issue where the mock data is not being supplied correctly. ...

Query parsing in JSON using the Elasticsearch Java API is what we need to focus

As I work with an elasticsearch database to store Contacts, I execute the following query. public String getAllContacts() throws IOException { SearchResponse response = client.prepareSearch("contact").get(); return response.toString(); } After ...

Are foreign characters the culprit behind the JSON parsing problem?

I am encountering an issue while attempting to parse a field containing JSON data returned from an API. The data includes various unusual characters like East Asian symbols and curly quotes, causing this error to appear. I am unsure of how to resolve it - ...

Changing the value of undefined properties in a JavaScript object

I am struggling to identify and replace null values with 0's in my object. I was able to access the correct member within the loop, but once it exited, the values were no longer assigned as 0. Working with objects in JavaScript is new to me, so I&apos ...

Is there a way to transform the SmartyStreets' jQuery.LiveAddress plugin into its JavaScript SDK?

My website currently utilizes the jQuery.LiveAddress plugin, however, it was deprecated and subsequently removed by SmartyStreets back in 2014. <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <s ...

Transforming the contents of a folder into a json document

I have a collection of files in directory A with the .txt extension, and I'm looking to create a JSON file for this specific directory (A) from another directory (B) that includes the names and locations of all the files. Can anyone guide me on how I ...

The Laravel controller is producing a JSON response that is coming back as undefined

Greetings! I am working with a JSON array and running the following code in my AJAX call: $('tbody').html(data.table_data); When I receive the response, it looks like this: [{"id":28,"fname":"tester","lname":"testlast","phone":"00000000","emai ...

What exactly does a module's scope entail in browsers and Node.js environments?

Can someone clarify the scope of a module in different environments like browsers and Node? I'm particularly interested in whether a module-level variable is initialized once for the entire application or multiple times. Is each import creating a new ...

Unable to properly access required file path through HTML source

I have a confidential folder named 'inc' where I store sensitive files such as passwords in php connection files. This folder is located at the same level as the 'public_html' folder. I successfully accessed php files with database conn ...

Issue with posting data to a JSON file using Vue and axios

I am encountering an issue with axis posting to a local .json file. The error I am receiving is: POST http://localhost:8080/todolist.json 404 (Not Found) TodoListEditor.vue?b9d6:110 Error: Request failed with status code 404 at createError (createErr ...

Looking to achieve a scroll effect with mix-blend-mode using JavaScript?

I am seeking a method to adjust the background color of a specific element based on the background itself. While CSS offers the mix-blend-mode property, I am looking to specify the color manually. Ideally, I would like to achieve the same effect using an ...

Sending a parameter value from a blade view in Laravel to a controller: tips and tricks

What is the best way to pass the value "{{$ item-> id}}" to a method in a controller? For example, if we have show.blade.php with the value: "{{$ item-> id}}" In MyController.php, how can we utilize this value within the method: public function ...

Is it more efficient to declare a variable or directly return the variable from the Element's getText() promise in Protractor?

I am facing a scenario where I need to retrieve the text of a web element using a promise and then extract a specific part of the string for further processing. Which example, the one at the top or the bottom, should I use? var id = element(by.binding( ...

Retrieve the value of a variable by using either an HTTP GET or POST request

Here's the HTML code snippet that I'm working with: <head> <h1>Sample Page</h1> </head> <body> <form method="POST" action=""> Enter Keyword <input type="text" name="key"> ...

What could be the reason why I am unable to choose my radio button? What error am I

The output can be found here... I am struggling to use a radio button and cannot seem to select it. Can someone please explain what issue I am facing? Any help would be greatly appreciated. const [value, setValue] = React.useState({ yes:"", no:"" ...

Create a typing effect in Javascript that mimics the user's input

Trying to simulate a typing effect with the sentence extracted from user input using JavaScript, but encountering some issues. Successfully capturing and displaying the input in the console with console.log(), however, incorporating the typing effect func ...

Troubleshooting Images in a React Application Integrated with WordPress API

I am struggling to understand why this GET request is consistently returning a 404 error. I have thoroughly tested the URL using Postman and everything seems to be in working order for the title and excerpt, but the images are causing some issues. Does a ...

Instructions for adding a Key every time a user clicks the space Key within an Input field

I built a Movie Search Page with the OMDB API. My current issue is that the API returns an error when searching for a movie with more than one word because the API URL requires a + key between each word. I am looking for a way to automatically add the + ke ...

Make a div with absolute positioning overflow outside of a div with relative positioning that is scrollable

I am facing an issue with two columns positioned side by side. The right column contains a tooltip that overflows to the left on hover. Both columns are scrollable and relatively positioned to allow the tooltip to follow the scroll. However, the tooltip is ...