Home > database >  How do I incorporate the index of an array while defining a property of said array within a class in
How do I incorporate the index of an array while defining a property of said array within a class in

Time:11-14

Sorry if the title makes no sense.. let me explain

Say I have the following 2d array.. the first array representing ice cream and the second representing milkshakes

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

Now I create a class that takes this array as input

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

Now I want to define a property called 'price' for each flavor of milkshake.

this.milkshakes[n].price = < a function that computes price based on value of n >

so that i can access them like this : cafe.milkshakes[0].price

So how do I incorporate the index 'n' of the array while defining the property

I haven't tried anything bcos I dont know how to even approach this ☹️

CodePudding user response:

You can do it in your constructor.

You can grab the names, and call map function on it and do whatever you want. Please check the following example. There, calculatePrice is a function that takes the index and returns 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 is a minimal answer.

UPDATE: For a detailed and improved answer: https://codesandbox.io/s/cafe-example-wxp2c4

CodePudding user response:

So, in the milkshakes array you need each item as an object data structure, not a string.

menu = [ ['vanilla', 'chocolate', 'almond'],
         [{ flavor: 'vanilla' }, { flavor: 'pineapple' }, { flavor: 'strawberry' }] ]

and then you can loop through and set the price, something like this.

menu.milkshakes.forEach((item, index) => item.price = index))

CodePudding user response:

you can use objects:

menu = [
  [
    {
      name: "vanilla",
      price: 200,
    },
    {
      name: "chocolate",
      price: 200,
    },
    {
      name: "almond",
      price: 200,
    },
  ],
  [
    {
      name: "vanilla",
      price: 200,
    },
    {
      name: "pineapple",
      price: 200,
    },
    {
      name: "strawberry",
      price: 200,
    },
  ],
];

and then:

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

now iceCreams and milshakes have the property price and name

example:

iceCreams[n].price
iceCreams[n].name
  • Related