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

  • A+
Category:Languages

I finally gave up and wrote a for loop to initialize a simple array of objects where each object has an incrementing counter 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 }; 

 


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}, (_, i) => ({id:i}))  console.log(sampleData)

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: