0

I'm trying to push data in a chart from a JSON output into multiple arrays:

var STORE_A = [];
var STORE_B = [];
var STORE_C = [];
var STORE_D = [];
var STORE_E = [];
var STORE_F = [];

In order to avoid an endless amount of lines in my script, I want to use a loop. I figured out how to do my loop but I cannot use my var just before ".push".

var storeName = ("STORE_"+json[i].Store);

storeName.push(value); // Should give me STORE_A.push(value); STORE_B.push(value);...

Here is a codepen of my issue https://codepen.io/BastienAustin/pen/bBQQQz

You can see the desired output by un-commenting around line 35.

Thank you for your help.

t.niese
  • 39,256
  • 9
  • 74
  • 101
Bastien Bastiens
  • 419
  • 6
  • 16
  • Are you just looking to automate the code after line 35? If so your json index matches your store index, you can just put your stores in an array and use the same lookup for which store to push to and which json value to grab – Marie Dec 15 '16 at 18:20
  • When asking questions make sure that all relevant informations are in the question itself. An external link to a complete example is nice, but the question itself should be written in a way that it is possible to understand the problem without looking into an external link, because that external link might not be reachable anymore in future. I updated your question so that it should be understandable without looking into the codepan link. – t.niese Dec 15 '16 at 18:36
  • Does this answer your question? ["Variable" variables in JavaScript](https://stackoverflow.com/questions/5187530/variable-variables-in-javascript) – Heretic Monkey Aug 29 '22 at 20:34

1 Answers1

3

What you want to do is the following:

Put your STORE_A to STORE_F in an object:

var Stores = {
  STORE_A: [],
  STORE_B: [],
  STORE_C: [],
  STORE_D: [],
  STORE_E: [],
  STORE_F: []
}

And then you can refer to them using:

Stores["STORE_"+json[i].Store].push(value);

Another way would be to just create an empty object:

var Stores = {};

And in your loop you could write:

Stores["STORE_"+json[i].Store] = Stores["STORE_"+json[i].Store] || [];
Stores["STORE_"+json[i].Store].push(value);

The value = value || [] construct will keep either the content of value if its value is not falsy, or will set it to [] if it is falsy.

To reduce redundancy in the names I would write:

Stores[json[i].Store] = Stores[json[i].Store] || [];
Stores[json[i].Store].push(value);

Then you could access it later using Stores.A, Stores.B, ...

t.niese
  • 39,256
  • 9
  • 74
  • 101