Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript create array of objects of length n [duplicate]

Tags:

javascript

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: '' })]
like image 533
bdoubleu Avatar asked Sep 26 '19 16:09

bdoubleu


People also ask

How do you get a list of duplicate objects in an array of objects with JavaScript?

To get a list of duplicate objects in an array of objects with JavaScript, we can use the array methods. to get an array of value entries with the same id and put them into duplicates . To do this, we get the id s of the items with the same id by calling map to get the id s into their own array.

How do you clone an array of objects?

it("creates separate objects in array", () => { const clone = deepClone(people); clone[0]. name = "Jack"; expect(clone[0]. name). toBe("Jack"); expect(people[0].

How do you duplicate an array in JavaScript?

Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable.

How do you create an array with the same value?

To create an array with N elements containing the same value: Use the Array() constructor to create an array of N elements. Use the fill() method to fill the array with a specific value. The fill method changes all elements in the array to the supplied value.


1 Answers

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)
like image 110
Code Maniac Avatar answered Sep 18 '22 09:09

Code Maniac