const data = [];
Array.from({ length: 1 }).forEach(() => {
data.push({
number: Math.floor(Math.random() * 10)
});
});
console.log(data)
I use above code to generate array of object but I used data as temporary variable, not sure if I can write it better.
CodePudding user response:
You don't need the forEach
invocation. Array.from()
accepts a callback function as the second argument:
const data = Array.from(
{ length: 3 },
() => ({ number: Math.floor(Math.random() * 10) }),
);
console.log(data);
CodePudding user response:
You can initialize an array using the []
;
const data = [{ number: Math.floor(Math.random() * 10) }];
Edit: Missed the part where you asked to use the Array.from
-function.