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
    },
    ...
]
3
  • What is the structure of data? Commented Nov 29, 2020 at 11:37
  • @DeanJames Updated my question. Didn't want to include it in the first place because it seems too cluttered. Commented Nov 29, 2020 at 11:45
  • Does this help? Commented Nov 29, 2020 at 12:19

1 Answer 1

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
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.