16

Is there a one-liner to create an array of objects of length n?

const arr = [
    { first_name: '', last_name: '' },
    { first_name: '', last_name: '' },
    { first_name: '', last_name: '' },
]

I've tried below but am getting SyntaxError: unexpected token: ':'

const arr = [...Array(3).map(x => { first_name: '', last_name: '' })]
ggorlen
  • 44,755
  • 7
  • 76
  • 106
bdoubleu
  • 5,568
  • 2
  • 20
  • 53
  • not to be smart, but you could minify your code to one line. for loops work good too. – sao Sep 26 '19 at 16:19
  • Map not working with empty array, b/c Array(3) set only length, but no elements there. To make map work you should fill your array first `const arr = [...Array(3).fill(1).map(...` – Julia Shestakova Sep 26 '19 at 16:24
  • Try this `Array.from({length:3}).map(x => ({first_name: '', last_name: ''}))` – Faisal Umair Sep 26 '19 at 16:31
  • @JuliaShestakova yes, but then the spread syntax is pointless. Typically it's one or the other, e.g., `[...Array(n)].map(() => ({}))` or `Array(n).fill().map(() => ({}))`. I don't recommend `fill` though--more typing and prone to aliasing bugs. – ggorlen Sep 21 '22 at 19:05

3 Answers3

25

You need to wrap return value by () whenever you want to return object from arrow function you need to wrap () else it will treat it as start of function body,

console.log([...Array(3).map(x => ({ first_name: '', last_name: '' }))])

Now you see error is gone but why the values are undefined ? because map doesn't loop over the empty slots you need to use fill

console.log([...Array(3).fill(0).map(x => ({ first_name: '', last_name: '' }))])

Or you can use Array.from

let arr = Array.from({ length: 3 } , () => ({ first_name: '', last_name: '' }))

console.log(arr)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • In version 2, what's the point of the spread syntax? I'd use either `fill` or spread, but not both. – ggorlen Sep 21 '22 at 19:04
2

You just need to wrap returned object in () but you can also use Array.from method instad.

const array = Array.from(Array(3), () => ({ first_name: '', last_name: '' }))
console.log(array)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
1

It is seen not as an object, you need to wrap the object in () and you need to use fill() for map to work.

const arr = [...Array(3).fill().map(x => ({ first_name: '', last_name: '' }))]
epascarello
  • 204,599
  • 20
  • 195
  • 236