I finally gave up and wrote a for loop to initialize a simple array of objects where each object has an incremented counter (id) as an attribute of the object. In other words, I just want:
var sampleData = [{id: 1},{id: 2},...];   I was hoping for a compact syntax I could just put on my return statement.
let sampleData = []; for (var p = 0; p < 25; p++){     sampleData.push({id: p}); }  return {     data: sampleData,     isLoading: true }; 
                You can initialize an array with Array constructor syntax using new keyword. The Array constructor has following three forms. Syntax: var arrayName = new Array(); var arrayName = new Array(Number length); var arrayName = new Array(element1, element2, element3,...
Use the fill() method to create an array filled with zeros, e.g. new Array(3). fill(0) , creates an array containing 3 elements with the value of 0 . The fill() method sets the elements in an array to the provided value and returns the modified array.
Array.from() is a nice way to do this. You can pass a {length: somlength} object or some other array-like object and a function that defines each item. The first argument (calling it _ just to indicate it's not used) to that function would be the item from an array we passed in (but we only passed in a length so it doesn't mean much), the second i is the index, which is used for your id:
let sampleData = Array.from({length: 10}, (_, id) => ({id}))    console.log(sampleData)  If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With