What is the best way to use the index of an array when setting a property of that array within a JavaScript class?

Apologies if the title is confusing, allow me to clarify

Imagine I have a 2d array representing different flavors of ice cream and milkshakes

menu = [ ['vanilla', 'chocolate', 'almond'],
         ['vanilla', 'pineapple', 'strawberry'] ]

Now, I am creating a class that takes this array as an input

class cafe{
  constructor(menu){
    this.iceCreams = menu[0]
    this.milkshakes = menu[1]
  }
}

I want to set a 'price' property for each flavor of milkshake.

this.milkshakes[n].price =  < a function that calculates price based on n >

This way, I can access them like so : cafe.milkshakes[0].price

How can I include the index 'n' of the array when defining the property?

I haven't attempted anything yet as I'm unsure how to proceed ☹️

Answer №1

If you want to achieve this functionality, you can implement it within your constructor method.

Simply extract the names from the data and utilize the map function to manipulate them as needed. Below is an example code snippet where the calculatePrice function determines the price based on the index:

class Cafe {
constructor (menu) {
    this.iceCreams = menu[0].map((flavor, index) => {
      return {
        flavor,
        price: calculatePrice(index)
      }
    });

    this.milkshakes = menu[1].map((flavor, index) => {
      return {
        flavor,
        price: calculatePrice(index)
      }
    });
}

This response provides a basic outline of how to approach the task at hand.

UPDATE: For a more comprehensive and enhanced solution, refer to: https://codesandbox.io/s/cafe-example-wxp2c4

Answer №2

For the array called milkshakes, ensure that each element is an object and not a string.

drinks = [ ['latte', 'cappuccino', 'espresso'],
         [{ type: 'latte' }, { type: 'matcha' }, { type: 'chai' }] ]

Then, you can iterate through the array to assign prices, similar to the following example.

drinks.milkshakes.forEach((item, index) => item.cost = index))

Answer №3

Utilize objects in your code:

itemList = [
  [
    {
      item: "apple",
      cost: 1.00,
    },
    {
      item: "banana",
      cost: 0.50,
    },
    {
      item: "orange",
      cost: 0.75,
    },
  ],
  [
    {
      item: "milk",
      cost: 2.00,
    },
    {
      item: "juice",
      cost: 1.50,
    },
    {
      item: "soda",
      cost: 1.25,
    },
  ],
];

Next, define a class like so:

class groceryStore{
  constructor(itemList){
    this.fruits = itemList[0]
    this.drinks = itemList[1]
  }
}

Now the fruits and drinks have properties of price and name

For example:

fruits[n].cost
fruits[n].item

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

Exploring AngularJS - Understanding how dependency injection works in services, factories, filters, and beyond

Currently, I am using plugins and libraries in my Angular app by directly referencing their functions/methods without considering dependency injection. This approach is common in most apps, but I want to optimize the use of these resources. One such libra ...

Correctly formatted onclick

How should I go about this? $chatterhtml .= '<span style="float:right;" > <a href="javascript:void(0);" onClick="deletecmnt(this, "'.$val['id'].'", "'.BASE_URL.'");" title="Delete Chatter">x</a&g ...

Finding indexes that are not being utilized

Is there a way to find unused indexes on an existing MYSQL installation without access to Percona tools? These instances are hosted on Amazon RDS, so traditional methods may not be feasible. I stumbled upon , but I'm curious if there are alternative ...

How can I improve the organization of my NPM scripts for better readability?

My primary testing process tool has become NPM scripts. However, as I continue to create more NPM scripts, the order and structure are becoming increasingly difficult to quickly interpret. Below is a snapshot of my current scripts: { "scripts": { ...

Encountering a window undefined error while using React-leaflet

I'm currently working on creating a map using react-leaflet and server-side react. To tackle the "ReferenceError: window is not defined" issue, I've implemented a map component and experimented with utilizing the useEffect hook for dynamic loadin ...

set up the router by defining the behavior for each route

My goal is to redirect the user back to the homepage when they click the browser's back arrow to return to the previous page. However, I'm facing an issue where I cannot go back to the previous page when I'm on the login page using the brow ...

How can I use AJAX/PHP to change a value in MySQL when a checkbox that was created dynamically is clicked?

Currently, I am working on a project where I need to create an admin panel. This admin panel will display a table with multiple entries, each row containing a checkbox. The purpose of these checkboxes is to activate or deactivate the respective entry on th ...

I'm currently facing an issue with toggling the visibility of a div using JavaScript

In my attempt to create a unique custom select menu using html, css, and javascript, I encountered an issue with toggling the display style of the div containing the options when clicking on the button (in this case, an arrow). HTML: <ul class="de ...

Would it be considered improper to apply ID's to DOM elements for the purpose of automation, as it may transform their CSS classes into individual entities?

Just thinking about the best approach for Automation (such as Selenium). I've been advised against using IDs on elements, as it could result in JS errors (in case of duplicate IDs) and make CSS classes unique. While I see the point, not having IDs can ...

Convert the date format to "DD-MM-YYYY"

When using the input type "date" as shown below: <input type="date" class="form-control input-sm pull-right" name="order_date" placeholder="Created At" id="l1" [(ngModel)]="order_date"> The result is displayed in "YYYY-MM-DD" format. I a ...

How can I use a Google extension to interact with buttons on a webpage?

In my project, I have created an extension file named github.js jQuery(document).ready(function($) { console.log('github.js'); // btn btn-primary shelf-cta var button = $('.btn.btn-primary.shelf-cta'); console.log('button. ...

Unable to modify the color of the title text on a card component using React Native Paper

Recently embarking on my journey with React Native and utilizing Paper for UI components. My current screen is structured with a card layout: {cardData.map((card, index) => { return( <Card key={index}> <Card.Title title="Card ...

Having an issue with redirecting in Jquery Ajax after a successful call

I am trying to redirect the user to google.com after a successful AJAX request. However, the success function does not seem to be working or getting called at all. Below is the code snippet for the AJAX request: $('.modal2c').click(function() { ...

Unable to submit live data due to unobtrusive validation issue in MVC 4.5

In our form, users can easily move items between multi-select boxes. Our setup includes MVC 4.5 and jQuery validate with Microsoft's unobtrusive javascript. One issue we encountered is that when the form is submitted, the values in the select boxes a ...

Encountering a Next.js prerendering issue when using getStaticPaths

I am currently developing a Next.js application. Here is the structure of my files: cpanearme -components -listitem.js -pages -home -index.js -firm -[id].js Below is the code for a list item that redirects to the dynamic rout ...

The AJAX functionality for $_POST requests appears to be malfunctioning

Seeking assistance with passing a value between a JavaScript file and PHP file when clicking a button. Despite attempting to echo the value upon button click, it is not displaying. Any insights as to what might be causing this issue would be much appreciat ...

Is there a way to include a different component without it automatically displaying within a div element?

Is there a way to make the Torrent component render without directly binding it to a DOM element? I am facing an issue with my Torrent Table Component as I want it to be populated with Torrent Components based on API data, but it's not rendering beca ...

Using an image as an onclick trigger for a JavaScript function

I am working on a registration page as part of my university project where users can create an account and store their information in a MySQL database. One feature I'm implementing is the ability for users to select an avatar picture. Below is the co ...

What is the best way to make an element's width match the width of the window?

When using the following code: $(my_div).width(window.innerWidth) The expected result is not achieved, as it does not take into account the vertical scrollbar. This causes the element to overflow the window, resulting in a horizontal scrollbar, which ca ...

Changing the background image of a specific div using CSS and JavaScript: a beginner's guide

I've been attempting to modify the background of a div in HTML using JS and CSS. Below is the code I've tried, but it doesn't seem to be working as expected. function changeBackground(previewPic) { var imgUrl = previewPic.src; conso ...