Say I have an array of functions:
let myArray = [foo, bar, baz];
and i want to convert that to an array of strings with the function names:
let myArrayAsStrings = ['foo', 'bar', 'baz'];
How can I do that?
I have tried doing
myArray.map(fn => fn.name)
however my babel config is i think mangling the function names, so it cannot be guaranteed that the name will be the same.
Wondering if there's some kind of 'convert var name to string' method I don't know about?
-
myArrayAsStrings = myArray.join(); try this oneVanns35– Vanns352020年03月29日 17:47:02 +00:00Commented Mar 29, 2020 at 17:47
-
@Vanns35 that stringifies it - which makes a string out of the entire function and its body. Have seen that before, and then people use regex / substr to find the name, but it feels a bit yuck.Lucas Arundell– Lucas Arundell2020年03月29日 18:43:27 +00:00Commented Mar 29, 2020 at 18:43
3 Answers 3
It’s unclear if foo, bar, and baz are normal functions (function foo() {}), unnamed functions (var foo = funtion () {}), or arrow functions (which can be only anonymous). fn.name will work only for the first case, the other two won’t have a name.
Theoretically, this could be a workaround:
var myArrayAsStrings = Object.keys({ foo, bar, baz });
This will first store each function as a property and then we can extract properties names from the object as an array of keys. The downside of this solution is that the order either cannot be guaranteed.
However, if there is some sort of uglification then the original names from the code will be lost.
Comments
Seems to be working fine, just add toString() at the end and push it into an array
var foo = function() {
console.log("Foo");
};
var bar = function() {
console.log("bar");
};
var baz = function() {
console.log("baz");
};
let myArray = [foo, bar, baz];
let myArrayAsStrings = [];
myArray.map(fn => myArrayAsStrings.push(fn.name.toString()));
console.log(myArrayAsStrings);
1 Comment
.name property cannot be guaranteed as Babel is uglifying the funciton namesEDIT: This answer is assuming there's an array of vars (as the title says), not an array of functions:
A one line solutuion :
myArray.toString().split(",")
1 Comment
myArray is an array of functions not an array of variables