0

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
    },
    ...
]
Amir Asyraf
  • 613
  • 1
  • 7
  • 18

1 Answers1

2

Here's a short example of how you can build the test object by looping over the data array:

const data = [
    {
        "amount": 10,
        "year": 2020,
        "month": 5
    },
    {
        "amount": 20,
        "year": 2019,
        "month": 5
    },
    {
        "amount": 30,
        "year": 2019,
        "month": 6
    }
]

let test = {};
data.forEach(item => {
  if (!test[item.year]) {
    test[item.year] = {};
  }

  test[item.year][item.month] = item.amount;
});

console.log(test)

This outputs:

{
  2019: {
    5: 20,
    6: 30
  },
  2020: {
    5: 10
  }
}
Dean James
  • 2,491
  • 4
  • 21
  • 29