The itemNumber variable stores the number. There are objects of the type cart.name1.price , cart.name2.price

How to put / substitute a variable in the place of a number? Maybe somehow it is necessary to screen?

cart.name+itemNumber+.price - swears to a point after +

  • You understand that this is a crutch, right? Your cart object does not explicitly match your needs. - D-side
  • there should be a structure {cars: [car: {name: 'Volvo', price: 30000}, car: {name: 'BMW', price: 35000}]} from the car in this case will get rid of - Serge Esmanovich
  • var name = 'name'+itemNumber; console.log(cart[name].price) var name = 'name'+itemNumber; console.log(cart[name].price) - mix
  • The structure is this, if there are comments on the implementation, I will listen to suggestions. name1:{ volume1:{ name:"111", volume:"0,9", price:"100" } }, name2:{ volume1:{ name:"222", volume:"0,9", price:"100" } } - KoteDoe
  • @SergeEsmanovich do not confuse car and cart :) The idea is correct, except that it makes no sense to explicitly specify keys in arrays, but I will assume that this is a reservation. - D-side

1 answer 1

To do this, use the bracket notation

 cart["name"+itemNumber].price