Converting a for loop into a fixed-size array?

I am currently developing a backbone application and have been given some sample code by the provider. The code includes a for loop that generates player names as 'player_1', 'player_2', and so on. However, I would like to manually enter player names such as Kobe, Lebron, etc instead of the generated format.

//generate 20 players
for(var i=1; i <= 20; i++) {
    players.add({
        id: i,
        name: 'player_' + i,
        score: Math.floor((Math.random()*20)+20)
    });
}

//generate 4 teams, and assign players to them at the same time...
for(var i=1; i <= 4; i++) {
    teams.add({
        id: i,
        name: 'team_' + i,
        players: new App.Collections.Players(players.filter(function(player) {
          return (player.id <= i*5 && player.id > (i-1)*5);
        }))
    });
}

I am unsure how to convert this into a static structure where I can manually input player names like 'mike', 'john' instead of the default 'player_1', 'player_2' format.

Upon console logging teams.toJSON(), I can see the objects in the console but I am struggling to extract the raw JSON data to understand how to create a hardcoded JSON array.

Answer №1

Based on your feedback, it seems like you are looking to create the following code snippet:

const names=['mike','john'];
for(let i=0; i < names.length; i++) {
    players.push({
        id: i,
        name: 'player_' + names[i],
        score: Math.floor((Math.random()*20)+20)
    });
}

Just like in other programming languages, you need to use the index number to access a specific element in an array.

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

Update MongoDB documents by inserting a new element into an array, calculated by multiplying a field with a constant value

Here's a MongoDB document that I am working with: { "_id" : ObjectId("5f6915c007f67a4588ec5f93"), "timestamp" : "2021-06-01T00:00:00Z", "sensor_id" : 1, "location_id" : 1, ...

Tips on connecting data within a jQuery element to a table of data

I am currently developing a program that involves searching the source code to list out element names and their corresponding IDs. Instead of displaying this information in alert popups, I would like to present it neatly within a data table. <script> ...

Guide to display half of an image and allow for full image viewing upon mouse hover

After creating my bootstrap 4 website, I encountered an issue with the code below where only half of the image is displayed initially due to a conflict in the code. It also fails to work properly when moving the mouse after shifting the whole image from ri ...

Issue with fs.createReadStream function: it is not recognized as a valid function

I'm currently developing a project in VUE that utilizes 'fs', and I have included my code below. async Upload(file){ let fs = require('fs'); console.log(file); console.log(this.dialogImageUrl); ...

What could be the reason for Angular showing the raw HTML code instead of

I'm currently diving into Angular and encountering an issue where my HTML isn't properly displaying the values I've set. It appears to only show the raw HTML. Here's a snippet from my HTML page: <p>to-do-items works!</p> < ...

Converting JSON data to Java objects with Jackson

I am looking to utilize Jackson for converting a JSON file that has the structure similar to [{"age":20,"name":"Bob"},{"age":35,"name":"Tom"}]. Let's say I have a User class, which is a Plain Old Java Object (POJO) containing variables like name and a ...

Adjust the counter by increasing or decreasing based on the selection or deselection of tags

Currently, I am utilizing Next.js to manage a question form that consists of multiple questions with multiple answers. Users have the option to select one or multiple tags for each question. When a user selects one or more tags to answer a question, it sho ...

Pull information from API and populate a dropdown menu in an Angular material select input

I am facing an issue with displaying data from an API in a mat select input field. I have tried to iterate over the data using a for loop but it is not working as expected. Can someone help me figure out how to properly populate the mat select input with d ...

Looping through multiple JSON requests using $.getJSON without the use of the let statement to ensure cross

Currently, I am developing a web application that loads JSON files into leaflet layers based on user actions. The code snippet below successfully accomplishes this task when using the "let" statement. However, removing it results in variables from the last ...

Using the indexOf method to arrange the data in the desired order

Greetings to all! Currently, I am working on implementing Angular fusion chart. My objective is to populate the data based on the product (json data) available. However, I am encountering an issue while utilizing the indexOf method in my fusion chart. All ...

Looking for a solution to organize the dynamically generated list items in an HTML page

I am currently working on a movie listing website where all the movies are displayed in sequence based on their #TITLE#. The webpage is generated automatically by the software using a template file. Here is the section of code in the template file that sho ...

Transmitting multiple file attachments to a PHP file through AJAX

In my form, I have the following HTML code: <input type="file" id="attachments" name="attachments" multiple> I've already implemented a JavaScript function that handles form submission using AJAX, but it doesn't handle uploaded files. Wi ...

Looking for a quick guide on creating a basic RESTful service using Express.js, Node.js, and Mongoose?

As a newcomer to nodejs and mongoDB, I've been searching high and low on the internet for a tutorial that combines express with node and mongoose. What I'm specifically looking for is how to use express's route feature to handle requests and ...

What is the best way to set up jest to generate coverage reports for Selenium tests?

I recently made the switch to using jest for testing my JavaScript project after encountering coverage issues with mocha and chai. While my unit tests are providing coverage data, my Selenium tests are not. I've tried various solutions found in outdat ...

Is there a library available for parsing JSON into a Dictionary of String-Object pairs in .NET?

I am looking for a way to convert a JSON string representing an object into a property bag (similar to a Dictionary) that I can utilize in C#. For example, if I have the following string: { "id":1, "name":"some name", "some parameter":2 } I aim to cre ...

Subcomponent in React is not rendering as expected

I have a primary React component with a subcomponent named AttributeInput. To prevent redundancy in my code, I moved some of the logic from the main component to a method within AttributeInput. My attempt at referencing this code looks like this: {this.s ...

Issue with dynamic code detected by Sys.Application.add_init

I am facing a challenge with an older application that I recently took over ownership of. My efforts to successfully run it have been partially fruitful, as I am encountering some strange behavior that seems to be related to Internet Explorer 11. Interesti ...

Most effective method for structuring a JSON format that contains recurring keys for every item within its array

Currently, I'm creating a JSON object that includes multiple addresses. My main concern is the potential for the JSON size to grow too large, which could impact browser performance and parsing speed in JavaScript. Each address includes keys such as "I ...

Node.js failing to log chat messages

The goal is to log the chat message entered by the user in the console (terminal). Currently, there seems to be an issue with logging and I'm struggling to debug it. Keep in mind that I am a novice when it comes to NodeJS and only have basic knowledge ...

Having trouble locating an element, Sammy?

I am encountering an issue while using Sammy for my SPA. The error message I receive is: [Sun Mar 29 2020 17:37:19 GMT+0300 (Eastern European Summer Time)] #main 404 Not Found get / Error: 404 Not Found get / at Sammy.Application.error (sammy-latest ...