Perform a function within an object

I am currently working on a project where I am using an array of objects to display random items on a canvas. The goal is to have each object display with a unique random color. However, the code I have written is causing every object to have the same color.

var arrayOfObjects = [
    {x: 1, y: 5, r: 10, color: pickColor}, //should have a random color
    {x: 2, y: 6, r: 10, color: pickColor}  // should have a different color
    //and so on...
];

I attempted to update the code by replacing the pickColor variable with a function that would be executed within each object to ensure they all receive a different color. However, I am facing difficulty in using this function to select a color from the color array.

Despite my efforts, the following code snippet does not achieve the desired outcome:

{x: 1, y: 5, r: 10, color: colorList[parseInt(Math.random() * colorList.length)]},

UPDATE: I have confirmed that this code is functioning correctly. The issue was unrelated and took some time to diagnose. Thank you for your assistance in troubleshooting.

Answer №1

Transform pickColor into a reusable function that can be invoked multiple times:

var colorList = ["#E57373", "#F06292", "#BA68C8", "#9575CD", "#7986CB", "#64B5F6", "#DCE775", "#AED581", "#81C784", "#FFD54F"];

function pickColor() {
    var randIndex = parseInt(Math.random() * colorList.length);
    return colorList[randIndex];
}

var arrayOfObjects = [
    {x: 1, y: 5, r: 10, color: pickColor()},
    {x: 2, y: 6, r: 10, color: pickColor()},
    //continue adding objects here...
];

By encapsulating the color picking functionality in a function, you avoid duplicating code for each object, achieving the same outcome as shown in your second code snippet.

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

Outputting specific lines from a text document based on their designated line numbers

Having an issue with implementing a while loop statement for the following question in relation to a txt file. 'Design a program that enables users to navigate through the text lines of any given text file. The program requests the user to input a ...

An Illustration of Basic Nested Controller within Directive Parameters

Check out this code snippet app.directive('hello', function() { return { restrict: "E", templateUrl: "/Angular/Modules/Selector.html", controller: function () { this.message = [enter the attribute message he ...

showing the response message from a post request using Vue.js and Axios

Within APIService.js, there's a function: createPatient(data){ const url = 'http://192.168.1.3/api/clinic/patient/add/'; return axios.post(url, data).then(resp => {return resp}); } In the script tag of my vue component: result ...

"Converting to Typescript resulted in the absence of a default export in the module

I converted the JavaScript code to TypeScript and encountered an issue: The module has no default export I tried importing using curly braces and exporting with module.exports, but neither solution worked. contactController.ts const contacts: String[ ...

What is the best way to populate a column in a dataframe using a function that requires another dataframe as input?

I am working with a dataframe that consists of two columns: A containing three types of texts, and B containing dates. df: A B CPI_x6 01/01/2015 CPI 01/01/2015 CPI_x9 01/03/2015 CPI 01/05/2015 In addition to this, I ha ...

Executing JavaScript function by clicking on <img>

I've been developing a website similar to YouTube, and I'm facing difficulties with the Like/Dislike feature for comments. Currently, I have implemented it in the following way: when a user clicks on an image (thumbsUp.png or thumbsDown.png), a ...

The Jenkins build on a specific branch is encountering issues with path exporting, causing it to fail

I have a set of files related to a new feature that I am trying to deploy through Jenkins. I have successfully deployed other branches in the past, but I am encountering difficulties with a specific branch. https://i.sstatic.net/BKVbH.png I believe the pro ...

Bringing Vue Components Together in Laravel: A Guide to Component Importation

Recently, I started learning Vue.js and I am looking to understand how to use component. Unfortunately, when I attempted to import my component into another component, it didn't work as expected. The framework I am currently using is Laravel 5.8 and I ...

Creating a new attribute within a JavaScript object by utilizing the properties of its sibling elements

Imagine a scenario where you have a complex array of objects structured like this: [ { "title": "Fundamentals", "order": 1, "lessonRef": "fundamentals", "children": [ { "title": "History", "order": 1, "lesso ...

Determine the amount of clicks and retrieve the URL of the clicked link in Selenium using Python

As a novice in the world of Selenium and Python, I am embarking on the journey of automating banner testing using Python along with Selenium Webdriver. My goal is to keep track of the number of clicks made, ensure that the URLs are redirecting to the corr ...

Setting up the Firebase emulator: should you use getFirestore() or getFirestore(firebaseApp)?

After delving into the process of connecting your app to the Firebase emulators like Firestore emulator, I came across the primary documentation which outlined the steps for Web version 9: import { getFirestore, connectFirestoreEmulator } from "fireba ...

Tips for Successfully Capturing Form Data with OnChange Event

On my website, I have set up a dedicated page for testing the functions I have developed, totaling around 30 to 40 so far. I have implemented a drop-down menu to list out these functions by name. When a function is selected, I trigger it using onChange wit ...

Can we include an option to display all pages in one row on a single page?

Is it possible to include an option to display all rows alongside the current options of 10, 15, and 100? I've been unable to locate this feature in the documentation: Check out the Codesandbox example: https://codesandbox.io/s/muidatatables-custom-t ...

How can I implement a thumbnail editing feature similar to Facebook's display image uploader in an Asp.net application using c#?

How can I upload an image and display a specific part of it in a thumbnail of a custom size? I also want to personalize the appearance of the thumbnail. ...

Show a picture without specifying its file location

Looking for Suggestions on a New Title I am interested in using a script as the source attribute for an image, like this : <img src="img.js"/> Note: I am open to using any programming language, whether it be javascript or php. Here is what my fol ...

Refresh the html page periodically by utilizing ajax every X seconds

Recently, I came across a post discussing the topic of automatically refreshing an HTML table every few seconds. The post can be found here. Currently, I am working with Rails and I want to achieve a similar functionality. However, I specifically want to ...

Confirm the presence of Cookie and save the data

I'm a beginner in the world of Javascript and Ajax, attempting to save a user's name using cookies. I have created a form where users can input their first name (identified by id = firstName). My goal is to remember this information so that the n ...

Updating a React event as it changes with each onChange event

Let's address a disclaimer before diving into the issue - for a quick look, visit this pen and type something there. The Scenario This is the JSX code snippet used in my render method: <input value={this.state.value} onChange={this.handleCh ...

Error: The function SomeFunction is not recognized as a valid function (Mongoose library)

Help needed! I'm encountering an error stating "TypeError: User.getUserByUsername is not a function at Strategy._verify (.../routes/users.js:65:10) var User = require('../models/user'); passport.use(new LocalStrategy( function(username, ...

Encountering a ReactJS error when retrieving an object assigned from an axios call to an

The code snippet below is causing me some confusion: import React, { Component } from 'react'; import axios from 'axios'; class Dashboard extends Component { state = { name : 'randomname', apiData: {} ...