-1

I have created the object with the forEach Loops as the follows,

var heading = { "Ranking": null, "Player": null}
var obj = {}
let array = [1, 2]
array.forEach(a =>{
    obj[a] = heading
})

and I got the object as the follows

{
'1': { Ranking: null, Player: null },
'2': { Ranking: null, Player: null }
}

and when I assign to the property of one key as follows

obj["1"]["Ranking"] = 100

the value is assigned to every key in the objects

{
'1': { Ranking: 100, Player: null },
'2': { Ranking: 100, Player: null }
}

the above assigned value syntax is work as intended with manually created object as the follows

var myObj = { "1" : {"Ranking" : null, "Player" : null}, "2": {"Ranking" : null, "Player" : null}}
myObj["1"]["Ranking"] = 100

{
'1': { Ranking: 100, Player: null },
'2': { Ranking: null, Player: null }
}

I am confused with whats leading to this, Can someone explain whats wrong here

jabaa
  • 3,902
  • 3
  • 6
  • 24
echo
  • 11
  • 2
  • 1
    There is no JSON in your question. The term JSON is not an alias for JavaScript literal. – jabaa May 09 '22 at 13:16
  • You're assigning references to the object you initially assign to `heading`, not copies of the object. – Quentin May 09 '22 at 13:19
  • @Quentin thanks fella, your answer is short but make me understand so easily after read articles accordingly – echo May 09 '22 at 13:52

0 Answers0