0

As the title suggests, I wish to use the name of an array as a string. I have tried some things but i'm not sure if it is even related to the problem i'm having.

3
  • Hi, please show some of what you tried so that everyone will be able to help you Commented Sep 12, 2018 at 12:19
  • what do you mean by 'name of an array'? Commented Sep 12, 2018 at 12:20
  • When I say name of array I mean something like "var arrayThing = x", i want it to return the string "arrayThing". As for my previous code, I think it is completely unrelated so I doubt it would help. Commented Sep 12, 2018 at 12:28

3 Answers 3

2

const getVariableName = varObj => Object.keys(varObj)[0];

const arr = [1, 2, 3];
const arrayName = getVariableName({arr});

console.log(arrayName);

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

Comments

0

You can set the name of an array explicitly like so

var arr = []
arr.name = "arr"

and refer to it later as so

console.log(arr.name)

BUT there's a problem with this- array declaration in javascript is essentially just a pointer to some location in memory. Several other variables could have the a different 'name' assigned to them, but all still point to the same array.

3 Comments

Is this the only way to get the name of a array(State it beforehand)?
See the answer by @KaomiDev, as it's better than mine. But just remember, this is not a great solution to your problem and will likely cause issues in the future.
Thanks, I will keep that in mind if I run into problems with it.
0

You can do Object.keys({myArray})[0].

Obs.: ES2017 is required.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.