Search code examples
javascriptarraysobjectarr

How do I create an array of individual objects Javascript


they all point to the same object "bestGamer" I don't want them to do that, I want that each cell in the array will be an individual object with different values in their props.

I want to do it static cause later I want to pass an array, I don't to push in runtime different values

const bestGamer = {
        "name" : "",
        "points" : 0    
}
arr2 = new Array(2).fill(bestGamer)
console.log("First:",arr2[0])
console.log("Second:",arr2[1]);    
arr2[0].name ="Yossi"
arr2[0].points++
arr2[1].name ="Dima"
arr2[1].points++
console.log("First:",arr2[0]);
console.log("Second:",arr2[1]);
console.log("Orignal Object",bestGamer);

enter image description here


Solution

  • You need to create a copy while placing it into newArray, fill(bestGamer) places same bestGamer on all indices so you end up having same reference at all indices

    let bestGamer = { a: 1,  b: 2 }
    let newArr = new Array(2).fill(0).map(v=> ({...bestGamer}))
    
    newArr[0].a = 10
    console.log(newArr)


    Instead of new Array you can use Array.from

    let bestGamer = { a: 1,  b: 2 }
    let newArr = Array.from({length:2}, () => ({...bestGamer}) )
    
    newArr[0].a = 10
    console.log(newArr)