How to propagate arguments if input is an array of arrays in JavaScript
Trying to propagate an array as arguments to a method join
on path
in node but no luck:
var path = require("path");
var paths = [__dirname];
var userInput = ["app", "js"];
paths.push(userInput);
var target = path.join.apply(null, paths);
I get:
TypeError: Arguments for path.join must be strings
One possible solution is to simply give the method a string of arguments. I don't even know if this is possible. But just curious if there is a trick in JavaScript in situations like this. Or do I totally disagree with this?
You are pushing array to array, resulting in
[ __dirname, [ 'app', 'js' ] ]
path.join
doesn't know what to do with these nested arrays. apply
does not magically smooth its entrance in any way. The error message from path.join
couldn't be clearer: he wants his arguments to be strings, not arrays. Use instead concat
to concatenate arrays:
var path = require("path");
var paths = [__dirname];
var userInput = ["app", "js"];
// Use concat here
paths = paths.concat(userInput);
var target = path.join.apply(null, paths);
An alternative would be
paths.push.apply(paths, userInput);
which will push elements userInput
on paths
one after the other.
If you are using ES6 you can use the spread operator and write it like:
paths.push(...userInput)
or
paths = [...paths, ...userInput]
or just directly
var target = path.join(...paths, ...userInput)
Actually the problem was that I rethought the problem. Instead of concatenating an array of paths with another array, I was pushing the array into an array of paths:
var path = require("path");
var paths = [__dirname];
var userInput = ["app", "js"];
paths.push(userInput); // x
The problem can only be avoided with help paths.concat(userInput)
. Then you can propagate arguments:
path.join.apply(null, paths.concat(userInput));
Thanks @torazaburo for pointing this out.