0

I am attempting to collect the variable name of an array without pre-defining said name as a seperate string.

So if you have const someArray = ['cow', 'cheese', 'big_cow', 'big_cheese'];

Is there a way to make a new variable, say let arrayNameString, that ends up being equal to 'someArray' dynamically?

I noticed some partial solutions utilized mapping the keys of a newly defined object as well as Object.getOwnPropertyNames() but I couldn't quite figure out how to translate that to my particular dynamic use-case.

About7Deaths
  • 681
  • 1
  • 5
  • 16
  • 2
    No, there's no pointers back from objects to variables, it's a one-way reference. What would you expect if two variables refer to the same array? – Barmar Jul 03 '19 at 16:20
  • 2
    If you think you need this, there's something wrong with your design. What are you really trying to do that requires getting the variable name from the array? – Barmar Jul 03 '19 at 16:22
  • You could use an object, like `const someArray = {name: "someArray", data: ['cow', 'cheese', 'big_cow', 'big_cheese']};` – Barmar Jul 03 '19 at 16:23
  • I am converting my dataset arrays to a CSV file, where the column names are equivalent to the array names, I'm trying to figure out if its possible to just have the name listed a single time instead of writing ```this.arrayName``` and ```'arrayName'``` every time. See https://stackoverflow.com/a/56874128/5067233 for my current solution. – About7Deaths Jul 03 '19 at 16:26
  • 1
    Any time you find yourself creating names with consecutive numbers in them, you should just be using an array and indexes, not names. – Barmar Jul 03 '19 at 16:33
  • That was for the sake of example, it has specific arbitrary names. – About7Deaths Jul 03 '19 at 17:05
  • use an object whose properties are the column names, not an array. Then you can use `Object.keys()` to get all the names. – Barmar Jul 03 '19 at 17:08

1 Answers1

1

Usually when I do this I make an object, as @Barmar suggested, but just use the name of the column as the key.

const data = { "arrayTitle" : [ 'data1', 'I\'m more data', 'etc.', 'etc.'] }

Then you can work accordingly using your loops to add data into the array:

// Add Data:
data["key"] = ['more data']
// or, provided the array already exists
data["key"].push('more things')

// Access Data:
for (const key of Object.keys(data)) {
   const dataItem = data[key]
}

Using this structure should be more than enough to transform into a CSV.

acupofjose
  • 2,159
  • 1
  • 22
  • 40