I bumped into this question (how to init an array like [{id: 1},{id: 2},...]
).
Accepted answer is:
let sampleData = Array.from({length: 10}, (_, i) => ({id:i}))
console.log(sampleData)
And there are plenty others.
However, I thought of template literals as a solution, but I can't figure out how to make it work.
What I have so far is:
var i = 0;
var arr = `[${"{id:++i},".repeat(10)}]`
console.log("As a string",arr);
console.log("Evaluated",eval(arr));
However, it uses eval
which I know it's wrong.
I also tried
var i = 0;
var arr = `[${"{id:${++i}},".repeat(10)}]`
console.log(arr);
But I have yet to somehow call the back ticks on this string (something like TemplateLiteralFunction.call
on arr
), to parse those expressions.
And instead of writting a tag function I'd just write a function called initArray(ofLength)
.
So, is there anyway you can use template literals without eval
or tag functions and achieve an array of a given length filled with values? Perhaps somehow nesting template literals?