How would you dynamically add/update a property of an object in Javascript?
For example, with PHP's associative array, it's super simple and intuitive. e.g.
$test = [];
foreach ($data as $key => $value) {
...
$test[$year][$month] += $amount;
}
var_dump(json_encode($test));
I can automatically update or add new item to the array. I'd get something like:
{
"2018": {
"5": 1110,
"6": 690
},
"2019": {
"9": 354,
"10": 531,
"12": 567
},
"2020": {
"1": 444,
"2": 100,
"4": 200,
"8": 1431
}
}
I have tried, in Javascript without success:
let test = {};
data.forEach(function (item, index) {
...
test[year] = {
[month]: amount
}
});
which yield something like:
{
"2018": {
"2": 1394000
},
"2019": {
"0": 3204000
},
"2020": {
"0": 1475000
}
}
The month gets replaced by whatever is last in the loop. Also I haven't been able to figure out how to add to the existing amount.
I'd prefer not to do a bunch of ifs to check if the object property already exists etc.
Or perhaps I'm approaching this the wrong way?
Edit:
Example of $data
or data
, which can have duplicate years and months.
[
{
"amount": 123,
"year": 2020,
"month": 5
},
{
"amount": 123,
"year": 2019,
"month": 3
},
...
]