I am attempting to create an array of dictionaries and then to iteratively update individual values in those dictionaries using Array.map(). It appears that every iteration, despite my referencing each individual dictionary by its index in the array, all dictionaries are being updated.
Here's a snippet that shows this behavior:
testarray = Array(5).fill({'number': 0});
testarray.map(function(element, index) {
testarray[index]['number'] = Math.random()
});
I'm a major greenhorn in Javascript and may be thinking too much in Python, but is there a way to circumvent this behavior, or to better accomplish my goal of creating a list of dictionaries where the individual values of each dictionary can be updated independently?
Edit: I'm adding an example to show that this behavior also applies when grabbing elements from other lists to insert into the list of dictionaries:
letterarray = ['a', 'b', 'c', 'd', 'e'];
testarray = Array(5).fill({'letter': 'x', 'number': 0});
testarray.map(function(element, index) {
testarray[index]['letter'] = letterarray[index]
testarray[index]['number'] = Math.random()
});
This ultimately returns:
[ { letter: 'e', number: 0.7262187794379416 },
{ letter: 'e', number: 0.7262187794379416 },
{ letter: 'e', number: 0.7262187794379416 },
{ letter: 'e', number: 0.7262187794379416 },
{ letter: 'e', number: 0.7262187794379416 } ]
As opposed to:
[ { letter: 'a', number: 0.7262187794379416 },
{ letter: 'b', number: 0.9870744758968584 },
{ letter: 'c', number: 0.16493191974189658 },
{ letter: 'd', number: 0.6403787941360672 },
{ letter: 'e', number: 0.49447691255595005 } ]
which is the desired behavior.