0

I have list of predefined elements names that should be added to object as entries, and this list can be dynamically changed. For example:

let myList = ['bundle_3', 'bundle_2', 'mainbook', 'bsbook']; // This list can contain any amount of different strings like this

And now I want to use this items as part of variables when I create new object, like this:

// Totals
  let totals = {
    bundle_3_total: 0,
    bundle_2_total: 0,
    mainbook_total: 0,
    bsbook_total: 0,
    bzgbook_total: 0,
  }

As you see this object elements names contain part from my list like {itemName} + "_total", concatenated. Is this possible to create object dynamically using some kind of placeholders inside variables to match items from list? This is easy to do in PHP (using placeholders inside variables names), but how to do this in JavaScript?

And for example I may need the same in variables, like:

instead of: let bundle_3_total = 500

I want to have something like:

const item_id = "bundle_3"
let {item_id}_total = 1000 // This should become like "let bundle_3_total = 1000 for code.

Is this possible? I am using this in ReactJS (in create-react-app) so there maybe some workarounds.

Dmitry
  • 499
  • 1
  • 3
  • 19
  • 1
    Yes, creating that object is easily possible, `totals[item_id+'_total'] = 0`. But no, doing the same in variables is not possible, and a bad idea anyway – Bergi Nov 25 '22 at 10:57

0 Answers0