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.

7
  • 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? Commented Jul 3, 2019 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? Commented Jul 3, 2019 at 16:22
  • You could use an object, like const someArray = {name: "someArray", data: ['cow', 'cheese', 'big_cow', 'big_cheese']}; Commented Jul 3, 2019 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 stackoverflow.com/a/56874128/5067233 for my current solution. Commented Jul 3, 2019 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. Commented Jul 3, 2019 at 16:33

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.