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: '' })]
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.
it("creates separate objects in array", () => { const clone = deepClone(people); clone[0]. name = "Jack"; expect(clone[0]. name). toBe("Jack"); expect(people[0].
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.
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.
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)
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