What is the best approach for iterating through the creation of Objects?

Here is a simplified version of the current code, with fewer rows and properties.

var row1 = new Object();
var row2 = new Object();
var row3 = new Object();
var row4 = new Object();
var row5 = new Object();
var row6 = new Object();
var row7 = new Object();
row1.name = "Hello World!";
alert(row1.name);

The above code does not achieve its intended purpose because each row variable needs individual declaration. However, I am faced with creating numerous row variables.

var row = [];
var row1 = [];
var row2 = [];
var row3 = [];
row.push(1); 
row[1].name = "Hello World";
alert(row[1].name);

If possible, how can I efficiently handle this situation?

Answer №1

let arrayOfRows = [];
for(let index = 0; index < 7; index++)
{        
    arrayOfRows.push(new Object());
}
arrayOfRows[0].title = "Greetings Earthlings!";
alert(arrayOfRows[0].title);

Answer №2

JavaScript allows you to create custom complex objects in a unique way:

//defining a complex object
ComplexObj = function(){
    var self = {
        'prop1': 'value1',
        'prop2': 'value2',
        'prop3': {
            'subprop1': 'subvalue1',
            'subprop2': 'subvalue2'
        },
        'prop4': [
            1, 2, 3, 4
        ]
    };

    return self;
};

//creating instances of the complex object
var rows = [];
var newObj1 = new ComplexObj();
newObj1.prop1 = 'newvalue1';

var newObj2 = new ComplexObj();
newObj2.prop3.subprop2 = 'newsubvalue2';

rows.push(newObj1);
rows.push(newObj2);

for (var i = 0; i < rows.length; i++){
    alert('row' + i + ': prop1=' + rows[i].prop1 + ' subprop2=' + rows[i].prop3.subprop2);
}

To see this in action, check out the demo link provided below. Pay attention to how newObj1.prop1 and newObj2.prop3.subprop2 are updated to showcase that newObj1 and newObj2 are distinct instances of ComplexObj.

http://jsfiddle.net/p5evg/1/

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

Problem concerning the window object in a React functional component

Hey there, I am currently facing a situation where I need to access the window object within my React component in order to retrieve some information from the query string. Here is an excerpt of what my component code looks like: export function MyCompone ...

Suggestions for placing a script under the scripts menu in Illustrator CS5.1

My script for Adobe Illustrator CS5.1 is not showing up in the scripts menu despite trying to place it in various directories such as: C:\Program Files\Adobe\Adobe Illustrator CS5.1\Presets\en_GB\Scripts\ C:\Progra ...

What is the list of NPM packages already included in the AWS Lambda execution environment?

I was surprised to discover that the aws-sdk NPM module comes preinstalled in AWS Lambda using nodejs8.10. I couldn't find any information online about this. Are there other node.js modules that are also pre-installed in AWS Lambda? ...

Issues with Firefox Protractor testing functionality

Trying to test a protractor on an angularjs application using Firefox 47 has been unsuccessful. Attempted downgrading to version 46.0.1 after researching on Stack Overflow, but still facing issues. Has anyone discovered a working solution for this? It seem ...

A guide to effectively converting and parsing a class object that includes Uint8Array elements

After stringifying a class object that contains a property in Uint8Array, and then parsing it later, the property is no longer in Uint8Array format. Here's an example: class Example { title:string; byteData:Uint8Array; ...

Choosing the content within a div and inserting it into an email

I have an email sender feature on my website where users can fill out input fields and hit send, resulting in me receiving an email. The text from all the input boxes is included in the email body. Additionally, there are some generated texts in divs with ...

Deactivate the submit button when the form is not valid in angularjs

I am currently facing a challenge with my form that contains multiple input fields. To simplify, let's consider an example with just two inputs below. My goal is to have the submit button disabled until all required inputs are filled out. Here is wha ...

What is the proper way to credit the glyphicons element in Twitter's bootstrap framework?

According to the section on icons in the Base CSS page of GitHub's Twitter bootstrap, Glyphicons Halflings were not originally available for free. However, thanks to an agreement between Bootstrap and the creators of Glyphicons, developers can now use ...

Having trouble exporting CSV files with Tamil fonts. Are you experiencing an error?

We are exploring various methods to display Tamil content in a CSV file with characters like "தூதுக்கடட". Can anyone provide assistance? mysqli_set_charset($db, "utf8mb4"); $query = $db->query("$reports"); if($query->num_rows > ...

What is the best method for sending a PHP variable to an AJAX request?

I am working with three files - my main PHP file, functions.php, and my JS file. My challenge is to pass a PHP variable to JavaScript. Below is a snippet from my MAIN PHP FILE: function ccss_show_tag_recipes() { //PHP code here } Next, here's t ...

Choose dropdown choices using Node.js, MySQL, and EJS

I am looking to create a dropdown list using data from my MySQL database. Specifically, I want to populate the names from the "customer" table in the select option of my "create budgets" form using EJS. However, I am encountering issues with passing EJS da ...

I'd like to know what sets next/router apart from next/navigation

Within Next.js, I've noticed that both next/router and next/navigation offer a useRouter() hook, each returning distinct objects. What is the reasoning behind having the same hook available in two separate routing packages within Next.js? ...

The Bootstrap tab feature is malfunctioning when a tab is using data-target instead of href

While developing bootstrap tabs for an Angular app, I decided to use the data-target attribute instead of the href attribute to avoid any interference with routes. Here's a snippet of how I structured the tabs: <ul class="nav nav-tabs" id="myTab"& ...

Unveiling the secrets to retrieving JSON array objects in HTML with the help of Angular!

Looking to display a JSON file in HTML, but struggling with syntax for deeply nested objects. { "questions": [ { "question": "Qw1", "answers": [ { "answers": "An1", "value": 25 }, { ...

Ways to limit date selection with JavaScript or jQuery

On my webpage, I have two date fields: fromDate and toDate. My goal is to prevent submission if the difference between the dates is more than 7 days. https://i.sstatic.net/65LLH.png Despite implementing a script for this purpose, it doesn't seem to ...

Issues with tangents in three.js compared to the VertexTangentsHelper with problems on display

After enabling the "vertexTangentsHelper" feature in THREE.js, I've noticed that the tangents on various geometries appear to be incorrect. I'm questioning whether these tangents are being miscalculated (possibly due to my shader output) or if t ...

Exhibit MongoDB collection information through PUG template (Issue: Undefined Array)

I am encountering an issue while attempting to showcase the data from my MongoDB "users" collection. I keep receiving an undefined error with the array. Within my user controller file, I have imported express, express.router, and my user model. Below is ...

Encountered an error: Trying to access 'location' property from undefined in express app

Encountered Issue : I am facing an error that is hindering me from fetching data from the HTML form. Every time I input values into the form and click the button to send the data to an API for saving it in the database, this error pops up: Cannot read pro ...

A guide on setting up a countdown timer in Angular 4 for a daily recurring event with the help of Rxjs Observable and the Async Pipe

I'm currently working on developing a countdown timer for a daily recurring event using Angular 4, RxJS Observables, and the Async Pipe feature. Let's take a look at my component implementation: interface Time { hours: number; minutes: numbe ...

I have written code in JavaScript, but now I am interested in converting it to jQuery

What is the best way to convert this to jQuery? showDish("balkandish1") function showDish(dishName) { var i; $(".city").css('display', 'none'); $("#" + dishName).css('display', 'block'); } ...