Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a functional way to init an array in JavaScript ES6?

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 }; 
like image 986
Pete Avatar asked Jul 26 '18 01:07

Pete


People also ask

How do you initialize an array in JavaScript?

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,...

How do you fill an array with 0?

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.


1 Answers

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)
like image 166
Mark Avatar answered Sep 21 '22 18:09

Mark