What is the best way to incorporate objHoles into every individual object?

I need to assign specific attributes to each player in a game. Each player should have different sets of holes, with each hole having its own win, lose, push, and points values ranging from 0-20.

Is there a simple way to accomplish this task?

As a beginner in javascript, I would greatly appreciate any feedback on the code below :D

   let players = document.querySelectorAll('#players div');
    let holes = document.getElementById('holes');
    let arrPlayers = [];
    let arrHoles = [];
    for (let a = 0; a < holes.length; a++) {
        arrHoles.push({
            win: false,
            lose: false,
            push: false,
            points: "2"
        });

    }
    console.log(arrHoles);
    players.forEach(function(index, value) {
        //Assigning attributes to each player
        arrPlayers.push({
            /*I WANT THIS TO BE ASSIGNED FOR EACH HOLE*/
            /*holes: [{
                win: false,
                lose: false,
                push: false,
                points: "2"
            }],*/
            name: players[value].childNodes[0].data,
            id: players[value].getAttribute("data-id")
        });
        //arrPlayers[value];
        //arrPlayers.push(arrHoles);
    });

Answer №1

To streamline your code, implement a function that generates the necessary array and then invoke it for each player:

function createPlayerArray() {
    let holes = document.getElementById('holes');
    let arrHoles = [];
    for (let a = 0; a < holes.length; a++) {
        arrHoles.push({
            win: false,
            lose: false,
            push: false,
            points: "2"
        });
    }
    return arrHoles
}

Utilize this function when initializing the players in your app:


...
arrPlayers.push({
   holes: createPlayerArray(),
   name: players[value].childNodes[0].data,
   id: players[value].getAttribute("data-id")
});
...

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

Using Vue: Triggering .focus() on a button click

My journey with vue.js programming started just yesterday, and I'm facing a challenge in setting the focus on a textbox without using the conventional JavaScript method of document.getElementById('myTextBox').focus(). The scenario is that i ...

Customize each Picker.Item element in React Native with unique styles

How can I style individual Picker.Items beyond just changing the text color? Additionally, what other props can be used for a Picker.Item? I am aware of "key", "value", "label", and "color". Are there any additional props available? I want to customize o ...

What is it about Next JS and React JS applications that causes them to use up so much cache?

"What causes Next.js and React.js applications to need a large cache, and how does this affect their performance and resource usage?" Refreshing constantly for even small changes in the application as a developer can be frustrating. Are there an ...

React Error: The property 'i' cannot be read as it is undefined

I am encountering an issue with my code: class Albs extends React.Component{ constructor(props){ super(props); this.state = { i: 0, anh: this.props.hinhanh[this.state.i] }; var hinhanh = ["1.png", "2.png", "3.png"]; this. ...

Node development does not operate continuously

I'm facing a minor issue with node-dev. I followed the instructions in the readme file and successfully installed it. However, when I run the command like so: node-dev somescript.js, it only runs once as if I used regular node without -dev. It doesn&a ...

Guide on how to return a JSON result as a Dictionary instead of an Array using Express.js

I need to format my response as a dictionary with specific key-value pairs, like so: { "id": 5928101, "category": "animal welfare", "organizer": "Adam", "title": "Cat Cabaret& ...

having difficulty sorting items by tag groups in mongodb using $and and $in operators

I'm currently trying to execute this find() function: Item.find({'tags.id': { $and: [ { $in: [ '530f728706fa296e0a00000a', '5351d9df3412a38110000013' ] }, { $in: [ ...

What is the best approach for overlaying random meshes onto a terrain using a heightmap in three.js?

I'm interested in plotting randomly generated meshes at the y-position that corresponds to the terrain's height in three.js. While browsing through the documentation, I came across the raycaster method, which seems like it could be useful. Howeve ...

What is the best way to generate page elements in AngularJS when the total number of pages is already known?

I have a project where I am developing an application that showcases a JSON of "users" in an HTML5 table. This application is built using Bootstrap 3 and AngularJS. My goal is to implement pagination for this table. Instead of having an array to iterate t ...

I am currently having trouble with req.query not functioning correctly within Next.js for reading query parameters

I am facing an issue while working with a REST API in Next.js 13. I have created the API, which can be accessed at http://localhost:3000/api/portfolio. However, when I try to filter the data using query parameters like http://localhost:3000/api/portfolio?s ...

Annoying jQuery animation error: struggling to animate smoothly and revert back. Callback function conundrum?!

I'm completely lost with what I have accomplished. My goal was to create an animation where an element slides in from a certain position and then slides back when another element is clicked. To achieve this, I included the second event within the call ...

Tips on concealing a div until the value of a specific field surpasses zero

In order to ensure that users focus on the first section of the form before proceeding, I plan to hide the last section until a specific field has a value greater than zero. Check out my HTML code below: <div class="fieldcontainer"> <label>E- ...

Step by step guide to implementing form step validation in a multi-step jQuery form with radio buttons

I have implemented the sample code provided in this link, with the addition of 2 extra form steps: LINK TO SAMPLE FORM My form consists of radio buttons (2 per page) instead of text boxes. How can I ensure that each form page is validated so that the for ...

Share an entire /folder through an express server

I am currently working on an express server setup, and I am looking to streamline my route handling for managing an entire directory structure. root /html /css /js /app.js /images /index.html /some-other.htm ...

Check the output of the ChildProcess after executing a shell command

I am currently running the ChildProcess function within a Nextjs API route and I am struggling to retrieve the value from it. const output = exec( "curl -s -v https://test.com/index.php", (err, stdout, stderr) => { if (err) { ...

The for loop finishes execution before the Observable in Angular emits its values

I am currently using a function called syncOnRoute() that returns a Promise. This function is responsible for synchronizing my data to the API multiple times based on the length of the data, and it returns a string message each time. However, I am facing a ...

AngularJS: The `$locationChangeStart` event

I am attempting to check the next token in the next, but I am encountering an error: TypeError: next.localStorage is not a function APP.JS .run(function ($rootScope, $location,$log,User) { $rootScope.$on("$locationChangeStart", function (event,nex ...

The anchor tag fails to trigger the onClick function in React

I'm having trouble updating the component state in my React app when clicking on an anchor tag within the render method. I've attempted to bind the function in the constructor, but the console.log statement is still not being called. Here's ...

The target for CountUp is not defined in React.js and is either null or undefined

I'm experiencing an issue with React.js while using the CountUp library. I've tried everything I can think of, but so far, nothing has worked. I even created a state to check if the component is ready to render CountUp. I'm unsure whether t ...

Is it possible to access the operating system's native emoji picker directly from a website?

While there are numerous javascript plugins and libraries available for allowing users to select emojis for text inputs, both Windows and Mac operating systems already have their own native emoji pickers accessible via ⊞ Win. or CTRL⌘Space. Is there a ...