Tet
Tet

Reputation: 5

Is there anyway to convert a array name into a string?

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.

Upvotes: 0

Views: 560

Answers (3)

Robert Purcea
Robert Purcea

Reputation: 281

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

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

console.log(arrayName);

Upvotes: 2

KaomiDev
KaomiDev

Reputation: 61

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

Obs.: ES2017 is required.

Upvotes: 0

mic
mic

Reputation: 4465

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.

Upvotes: 0

Related Questions